/**
 * @author bumz
 */

add_rpx_again = function(){
	if ($('.rpx_popup_table').length == 0) {
		$('body').append('<script src="https://rpxnow.com/openid/v2/widget" \
		        type="text/javascript"></script> \
		<script type="text/javascript"> \
		  RPXNOW.token_url = "' + rpx_token_url + '"; \
		  RPXNOW.domain = "' + rpx_domain + '"; \
		  RPXNOW.overlay = ' + rpx_overlay + '; \
		  RPXNOW.language_preference = "' + rpx_language + '"; \
		  RPXNOW.show(); \
		</script>');
	}
};

Ext.onReady(function(){
	Ext.QuickTips.init();

	// turn on validation errors beside the field globally
	Ext.form.Field.prototype.msgTarget = 'side';
	
	var date = new Date();
    var years = [];
    var monthes = [];
    for (var i=date.getFullYear();i<date.getFullYear() + 10;i++) {
        years.push([i, i]);
    }
    
    for (var i=1;i<13;i++) {
        monthes.push([i, i]);
    }
	
	var fp2 = new Ext.FormPanel({
		frame: true,
		title: langlines.user_registration_step_2,
		labelWidth: 110,
		width: 670,
		bodyStyle: 'padding:0;',
		items: [{
			layout:'column',
			items:[{
				columnWidth:.7,
				style: 'padding-left: 15px;',
				layout: 'form',
				items: [{
						html: '<div class="register_with_text">' + langlines.user_register_linktive + '</div>',
						style: 'padding-bottom: 6px;'
					},{
					xtype: 'fieldset',
					//xtype: 'form',
					autoHeight:true,
		            defaults: {width: 210},
		            //defaultType: 'textfield',
					//itemCls: 'x-check-group-alt',
					//fieldLabel: 'Custom Layout<br />(w/ validation)',
					allowBlank: false,
					items: [{
						fieldLabel: '<span class="settings_notice">' + langlines.user_username + '</span>',
						name: 'username',
						id: 'username',
						vtype: 'readable',
						width: '250px',
						allowBlank:false,
						xtype: 'textfield',
						minLength: 5,
						maxLength: 254,
						validator: function (val)
                        {
                            var obj = this;
                                Ext.Ajax.request({
                                    url: base_url + 'user/is_username_busy',
                                    method: 'POST',
                                    success: function(responseObject){
                                        //Ext.MessageBox.hide();
                                        var resultInfo = Ext.util.JSON.decode(responseObject.responseText);
                                        
										if(resultInfo.status) {
                                            obj.markInvalid(resultInfo.message);
											
                                        } else {
											return true;
                                        }
                                    },
                                    failure: function(){
                                        //Ext.MessageBox.hide();
                                        return langlines.main_server_error;
                                    },
                                    params: {
                                        username: val
                                    }
                                });
                            return true;
                        }
					},{
						fieldLabel: '',
						html: '<div></div>',
						style: 'padding-bottom: 18px'
					},{
						fieldLabel: '<span class="settings_notice">' + langlines.user_password + '</span>',
						name: 'password',
						id: 'password',
						inputType: 'password',
						width: '250px',
						allowBlank:false,
						xtype: 'textfield',
						minLength: 5,
						maxLength: 254
					},{
						fieldLabel: '<span class="settings_notice">' + langlines.user_rep_password + '</span>',
						name: 'conf_password',
						id: 'conf_password',
						inputType: 'password',
						width: '250px',
						allowBlank:false,
						xtype: 'textfield',
						minLength: 5,
						maxLength: 254,
						vtype: 'password',
						initialPassField: 'password'
					},{
						fieldLabel: '',
						html: '<div></div>',
						style: 'padding-bottom: 18px'
					},{
						xtype: 'textfield',
						fieldLabel: '<span class="settings_notice">' + langlines.main_email_address + '</span>',
						name: 'email',
						id: 'email',
						vtype: 'email',
						width: '250px',
						allowBlank:false,
						validator: function (val)
						{
							var obj = this;
								Ext.Ajax.request({
									url: base_url + 'user/ajax_get_mail',
									method: 'POST',
									success: function(responseObject){
										//Ext.MessageBox.hide();
										var resultInfo = Ext.util.JSON.decode(responseObject.responseText);
										if(resultInfo.status)
										{
											return true;
										}
										else
										{
											obj.markInvalid(resultInfo.message);
										}
									},
									failure: function(){
										//Ext.MessageBox.hide();
										return langlines.main_server_error;
									},
									params: {
										email: $('#email').val()
									}
								});
							return true;
						}
					},{
						fieldLabel: '',
						html: '<span>' + langlines.user_reg_eml_notice + '</span>',
						style: {'padding-left': '120px'},
						width: '245px'
					},{
						fieldLabel: '',
						html: '<div></div>',
						style: 'padding-bottom: 10px;border-bottom:1px solid #e0e0e0;margin-bottom: 8px',
						width: '375px'
					},{
						xtype: 'textfield',
						fieldLabel: langlines.user_voucher,
						name: 'passcode',
						id: 'passcode',
						vtype: 'alphanum',
						width: '250px',
						allowBlank:true
					},{
						fieldLabel: '',
						html: '<div></div>',
						style: 'padding-bottom: 8px'
					},{
						xtype: 'textfield',
						fieldLabel: langlines.user_reffered_by,
						name: 'referred_by',
						id: 'referred_by',
						width: '250px',
						allowBlank:true,
						value: referrer_txt
					},{
						//fieldLabel: langlines.main_captcha,
						html: cap + '<button id="captcha-change"></button>',
						style: 'padding: 5px;margin-top: 15px;padding-left: 115px;border-top:1px solid #e0e0e0;',
						width: '255px'
					},{
						xtype: 'textfield',
						fieldLabel: '<span class="settings_notice">' + langlines.main_captcha_text + '</span>',
						name: 'captcha',
						id: 'captcha',
						vtype: 'alphanum',
						width: '250px',
						allowBlank:false

					}]
				}]
			},{
				columnWidth:.3,
				layout: 'form',
				
				items: [{
					html: '<div class="register_with_text">' + langlines.user_register_3party + '</div>'
				},{
					html: '<div><a class="rpxnow" onclick="RPXNOW.show();return false;" \
								href="https://' + rpx_domain + '/openid/v2/signin?token_url=' + rpx_token_url + '">\
								<img alt="" src="' + base_url + 'images/' + template_name + '/rpx_register.jpg" /></a></div>'
				},{
					layout: 'form',
					style:"border: 1px solid #BEBEBE; padding: 5px;margin-top: 7px;",
					items: [{
						html: '<div>' + langlines.user_resend_text_1 + '</div>',
						style: 'padding-bottom: 20px'
					},{
						html: '<a href="#" rel="resend_activation">' + langlines.user_resend_text_2 + '</a>',
						style: ''
					}]
				}]
			},{
                columnWidth:.64,
                layout: 'form',
                labelWidth: 135,
                labelAlign: 'right',
                items: [{
                    html: '<div class="register_payments">' + langlines.user_subscription_plan + '</div>'
                },{
                    fieldLabel: '<span class="settings_notice">' + langlines.user_choose_plan + '</span>',
                    name: 'plan_type',
                    id: 'plan_type',
                    store: new Ext.data.SimpleStore({
                        fields: ['key', 'value'],
                        data : [
                            [langlines['user_plan' + '_1'], langlines['user_plan' + '_1']],
                            [langlines['user_plan' + '_2'], langlines['user_plan' + '_2']],
                            [langlines['user_plan' + '_3'], langlines['user_plan' + '_3']]
                        ]
                    }),
                    allowBlank:false,
                    xtype: 'combo',
                    valueField:'key',
                    displayField:'value',
                    mode: 'local',
                    triggerAction: 'all',
                    selectOnFocus:true,
                    anchor: '100%',
                    validator: function (val)
                	{
						//IF IS BETA
                    	/*var plan_type = $('#plan_type').val();
                        var pay_opt = $('#pay_opt').val();
                        var result;
                        if (plan_type != '' && pay_opt != '') {
                            if (plan_type == 'premium'    && pay_opt == 'Monthly') {result = langlines.user_plan_2_monthly_description;}
                            else if (plan_type == 'premium'    && pay_opt == 'Yearly')  {result = langlines.user_plan_2_yearly_description;}
                            else if (plan_type == 'enterprise' && pay_opt == 'Monthly') {result = langlines.user_plan_3_monthly_description;}
                            else if (plan_type == 'enterprise' && pay_opt == 'Yearly')  {result = langlines.user_plan_3_yearly_description;}
                            else {result = '';}
                            if (result != '') {
                                $('#money_calculate').text(result);
                                $('#money_calculate_holder').show();
                            } else {
                            	$('#money_calculate_holder').hide();
                            }
                        } else {
                            $('#money_calculate_holder').hide();
                        }
                        if (plan_type == 'freemium') {*/
                            $('#payment_details').hide();
                            $('#express_checkout_box').hide();
                            $('#payment_prop').hide();
                        /*} else {
                            $('#payment_details').show();
                            $('#express_checkout_box').show();
                            $('#payment_prop').show();
                        }*/
                        return true;
                    }
                }]
            },{
            	columnWidth:.64,
                layout: 'form',
                labelWidth: 135,
                labelAlign: 'right',
                id: 'payment_prop',
                items: [{
                    fieldLabel: langlines.user_payment_options,
                    name: 'pay_opt',
                    id: 'pay_opt',
                    store: new Ext.data.SimpleStore({
                        fields: ['key', 'value'],
                        data : [
                            ['Month', langlines['user_pay_opt' + '_1']],
                            ['Year', langlines['user_pay_opt' + '_2']]
                        ]
                    }),
                    allowBlank:false,
                    xtype: 'combo',
                    valueField:'key',
                    displayField:'value',
                    mode: 'local',
                    triggerAction: 'all',
                    emptyText: '',
                    selectOnFocus:true,
                    anchor: '100%',
                    validator: function (val)
                    {
                        var plan_type = $('#plan_type').val();
                        var pay_opt = $('#pay_opt').val();
                        var result;
                        if (plan_type != '' && pay_opt != '') {
                            if (plan_type == 'premium'    && pay_opt == 'Monthly') {result = langlines.user_plan_2_monthly_description;}
                            else if (plan_type == 'premium'    && pay_opt == 'Yearly')  {result = langlines.user_plan_2_yearly_description;}
                            else if (plan_type == 'enterprise' && pay_opt == 'Monthly') {result = langlines.user_plan_3_monthly_description;}
                            else if (plan_type == 'enterprise' && pay_opt == 'Yearly')  {result = langlines.user_plan_3_yearly_description;}
                            else {result = '';}
                            if (result != '') {
                                $('#money_calculate').text(result);
                                $('#money_calculate_holder').show();
                            } else {
                                $('#money_calculate_holder').hide();
                            }
                        } else {
                            $('#money_calculate_holder').hide();
                        }
						//IF IS BETA
                        //if (plan_type == 'freemium') {
                            $('#payment_details').hide();
                            $('#express_checkout_box').hide();
                            $('#payment_prop').hide();
                        /*} else {
                            $('#payment_details').show();
                            $('#express_checkout_box').show();
                            $('#payment_prop').show();
                        }*/
                        return true;
                    }
                },{
                    html: '<div id="money_calculate_holder"><span style="float:left; font:11px Arial, sans-serif; color:#838383; text-align:right; padding:6px 5px 3px 0; width:135px;">' + langlines.user_payment_total_due + '</span><div id="money_calculate"></div></div>',
                    style: 'font-size:18px; font-weight:bold; margin-bottom:10px; color:#262626;'
                }]
            }/*,{
                columnWidth:.64,
                layout: 'form',
                labelWidth: 135,
                labelAlign: 'right',
                id: 'payment_details',
                items: [{
                	html: '<div class="register_payments">' + langlines.user_registration_payment_details + '</div>'
                },{
                    fieldLabel: langlines.user_cc_type,
                    name: 'cc_type',
                    id: 'cc_type',
                    store: new Ext.data.SimpleStore({
                        fields: ['key', 'value'],
                        data : [
                            [1, langlines['user_card_type' + '_1']],
                            [2, langlines['user_card_type' + '_2']],
                            [3, langlines['user_card_type' + '_3']],
                            [4, langlines['user_card_type' + '_4']]
                        ]
                    }),
                    allowBlank:true,
                    xtype: 'combo',
                    valueField:'key',
                    displayField:'value',
                    mode: 'local',
                    triggerAction: 'all',
                    emptyText: '',
                    selectOnFocus:true,
                    anchor: '100%'
                },{
                    xtype: 'textfield',
                    fieldLabel: langlines.user_first_name,
                    name: 'first_name',
                    id: 'first_name',
                    allowBlank: true,
                    anchor: '100%'
                },{
                    xtype: 'textfield',
                    fieldLabel: langlines.user_last_name,
                    name: 'last_name',
                    id: 'last_name',
                    allowBlank: true,
                    anchor: '100%'
                },{    
                    xtype: 'textfield',
                    fieldLabel: langlines.user_cc_number,
                    name: 'cc_number',
                    id: 'cc_number',
                    allowBlank: true,
                    anchor: '100%'
                },{
                    xtype: 'textfield',
                    fieldLabel: langlines.user_cv2_number,
                    name: 'cv2_number',
                    id: 'cv2_number',
                    allowBlank: true,
                    anchor: '100%'
                },{
                	boxLabel: langlines.user_emails_dailyrep_long,
                    layout:'column',
                    items:[{
                        columnWidth:.5,
                        layout: 'form',
                        items: [{
                            fieldLabel: langlines.main_expiration_year,
                            name: 'exp_year',
                            id: 'exp_year',
                            store: new Ext.data.SimpleStore({
                                fields: ['key', 'value'],
                                data : years
                            }),
                            allowBlank:true,
                            xtype: 'combo',
                            valueField:'key',
                            displayField:'value',
                            mode: 'local',
                            triggerAction: 'all',
                            selectOnFocus:true,
                            anchor: '100%'
                        }]
                    },{
                        columnWidth:.5,
                        layout: 'form',
                        items: [{
                            fieldLabel: langlines.main_month_to_expire,
                            name: 'exp_month',
                            id: 'exp_month',
                            store: new Ext.data.SimpleStore({
                                fields: ['key', 'value'],
                                data : monthes
                            }),
                            allowBlank:true,
                            xtype: 'combo',
                            valueField:'key',
                            displayField:'value',
                            mode: 'local',
                            triggerAction: 'all',
                            selectOnFocus:true,
                            anchor: '100%'
                        }]
                    }]
                }]
			},{
                columnWidth:.3,
                layout: 'form',
                id: 'express_checkout_box',
                align: 'right',
                style: 'float:right; text-align:center; padding-top:20px;',
                items: [{
                    html: '<div class="register_with_text">' + langlines.main_express_checkout + '</div>'
                },{
                	html: '<a id="express_checkout" href="#"><img height="37" width="143" alt="" src="/images/linktive/paypal_btn.gif" /></a>'
                }]
            }*/,{
            	columnWidth:.64,
                style: 'padding: 10px 0 0 140px; margin:0; float:left',
                layout:'form',
                items: [/*{
                    style: 'float:left;',
                    align: 'left',
                    xtype: 'button',
                    text: langlines.main_previous,
                    handler: function(){
                        $('#frm1').show();
                        $('#frm2').hide();
                    }
                
                },*/{
                    style: 'float:right;',
                    align: 'right',
                    xtype: 'button',
                    text: langlines.main_finish,
                    handler: function(){
                       if(fp2.getForm().isValid() && fp.getForm().isValid()){
                            Ext.MessageBox.show({
                                msg: langlines.user_registering,
                                progressText: langlines.main_please_wait,
                                width:300,
                                wait:true,
                                waitConfig: {interval:200},
                                icon:'download_icon'
                            });
                            
                            var dataSend = fp2.getForm().getValues(false);
                            var plan = fp.getForm().getValues(false);
                            dataSend.plan = plan.plan;
                            
                            Ext.Ajax.request({
                                url: base_url + 'user/ajax_opt_register',
                                method: 'POST',
                                success: function(responseObject){
                                    Ext.MessageBox.hide();
                                    var resultInfo = Ext.util.JSON.decode(responseObject.responseText);
                                    if(resultInfo.status)
                                    {
                                        showInfoMessageProc(resultInfo.message, function(btn_pressed){
                                            //if (btn_pressed == 'ok') {
                                                window.location.href = resultInfo.redirect;
                                            //}
                                        });
                                    }
                                    else
                                    {
                                        if (typeof(resultInfo.captcha) != 'undefined') {
                                            $('#captcha-image').attr('src', resultInfo.captcha);
                                            //console.log(resultInfo.captcha);
                                            Ext.getCmp('captcha').setValue('');
                                        }
                                        Ext.getCmp('password').setValue('');
                                        Ext.getCmp('conf_password').setValue('');
                                        showWarningMessage(resultInfo.message);
                                    }
                                },
                                failure: function(){
                                    Ext.MessageBox.hide();
                                    showErrorMessage(langlines.main_server_error);                                                        
                                },
                                params: dataSend
                            });
                            
                        }
                        else
                        {
                            showErrorMessage(langlines.main_please_check_correctness_data);                                
                        }
                    }
                }/*,{
                    style: 'float:right; margin-right:10px;',
                    align: 'right',
                    xtype: 'button',
                    text: langlines.main_reset,
                    handler: function(){
                        fp2.getForm().reset();
                    }
                }*/]
            }]
		}]
	});
	
	fp2.on('render', function(){
		
	});
	
//	fp2.initValue(function(){
//        if(this.value !== undefined){
//            this.setValue(this.value);
//        }else if(!Ext.isEmpty(this.el.dom.value) && this.el.dom.value != this.emptyText){
//            this.setValue(this.el.dom.value);
//        }
//        
//        this.originalValue = this.getValue();
//    });
	
	fp2.render('frm2');
	
	var fp = new Ext.FormPanel({
		frame: true,
		title: langlines.user_registration_step_1,
		labelWidth: 210,
		//width: 900,
		width: 600,
		renderTo:'frm1',
		bodyStyle: 'padding:0 10px 0;',
		items: [{
			layout:'column',
			style: 'padding-left: 200px;',
			defaults: {width: 135},
			items:[{
				columnWidth:1,
				layout: 'form',
				items: [{
					html: '<img src="' + base_url + 'images/linktive/option_private_beta.png' + '" alt="' + langlines['user_option' + '_1'] + '" />'
				}]
			}]
		},
		{
			xtype: 'radiogroup',
            itemCls: 'x-check-group-alt',
            fieldLabel: langlines.user_choose_plan,
            allowBlank: false,
            anchor: '95%',
			
			defaults: {width: 135},
			items: [{
                    columnWidth: '1.0',
                    items: [
                        {boxLabel: langlines['user_option' + '_1'], name: 'plan', inputValue: 1, checked: true}
                    ]
                }
			/*,{
				columnWidth: '.20',
				items: [
					{boxLabel: langlines['user_option' + '_2'], name: 'plan', inputValue: 2},
				]
			},{
				columnWidth: '.20',
				items: [
					{boxLabel: langlines['user_option' + '_3'], name: 'plan', inputValue: 3},
				]
			},{
				columnWidth: '.20',
				items: [
					{boxLabel: langlines['user_option' + '_4'], name: 'plan', inputValue: 4},
				]
			},{
				columnWidth: '.20',
				items: [
					{boxLabel: langlines['user_option' + '_5'], name: 'plan', inputValue: 5},
				]
			}*/]
		}],
		buttons: [{
			text: langlines.main_reset,
			handler: function(){
				fp.getForm().reset();
			}
		},{
			text: langlines.main_next,
			handler: function(){
			   if(fp.getForm().isValid()){
					$('#frm1').hide();
					$('#frm2').show();
				}
			}
		}]
	});
	
	var resend_activation_form =  new Ext.FormPanel({
		labelWidth: 110,
		width: 360,
		xtype:'fieldset',
        style: 'border:none;padding:12px;',
        title: '',
		ctCls: 'no_form_bck',
        autoHeight:true,
		items: [{
			layout:'column',
			items:[{
				columnWidth:1,
				layout: 'form',
				items: [{
					fieldLabel: langlines.main_email_address,
					name: 'resend_activation',
					id: 'resend_activation',
					width: '250px',
					allowBlank:false,
					xtype: 'textfield',
					minLength: 1,
					maxLength: 250,
					vtype: 'email'
				}]
			}]
		}]
	});
	
	var activation_win = null;
	Ext.select('a[rel="resend_activation"]').on('click', function(){
		
		if(!activation_win){
            activation_win = new Ext.Window({
                layout      : 'fit',
                width       : 440,
                height      : 150,
                closeAction :'hide',
                plain       : true,
                items       : resend_activation_form,
				title		: langlines.user_resend_window_text,
                buttons: [{
                    text     : langlines.main_ok,
					cls: 'btn_lowercase',
					handler: function(){
						if (resend_activation_form.getForm().isValid()) {
							Ext.MessageBox.show({
								msg: langlines.user_preset_saving,
								progressText: langlines.main_please_wait,
								width: 300,
								wait: true,
								waitConfig: {
									interval: 200
								},
								icon: 'download_icon'
							});
							
							Ext.Ajax.request({
								url: base_url + 'user/ajax_resend_activation',
								method: 'POST',
								success: function(responseObject){
									Ext.MessageBox.hide();
									var resultInfo = Ext.util.JSON.decode(responseObject.responseText);
									if (resultInfo.status) {
										resend_activation_form.getForm().reset();
										activation_win.hide();
										showInfoMessage(resultInfo.message);
									}
									else {
										showWarningMessage(resultInfo.message);
									}
								},
								failure: function(){
									Ext.MessageBox.hide();
									showErrorMessage(langlines.main_server_error);
								},
								params: {
									'email': Ext.getCmp('resend_activation').getValue()
								}
							});
						}
					}
                },{
                    text     : langlines.main_close,
					cls		 : 'btn_lowercase',
                    handler  : function(){
                        activation_win.hide();
                    }
                }]
            });
        }
		
		activation_win.show();
		
		return false;
	});
	
    
	
	$('#captcha-change').click(function(){
		$.ajax({
			method: 'post',
			dataType: 'json',
			url: base_url + '/user/ajax_change_captcha',
			success: function(data) {
				$('#captcha-image').attr('src', data.captcha);
			}
		});
		return false;
	});
	
	$('#express_checkout').click(function(){
        if(fp2.getForm().isValid() && fp.getForm().isValid()){
            Ext.MessageBox.show({
                msg: langlines.user_registering,
                progressText: langlines.main_please_wait,
                width:300,
                wait:true,
                waitConfig: {interval:200},
                icon:'download_icon'
            });
            
            var dataSend = fp2.getForm().getValues(false);
            var plan = fp.getForm().getValues(false);
            dataSend.plan = plan.plan;
            dataSend.trigger_checkout = true;
            
            Ext.Ajax.request({
                url: base_url + 'user/ajax_opt_register',
                method: 'POST',
                success: function(responseObject){
                    Ext.MessageBox.hide();
                    var resultInfo = Ext.util.JSON.decode(responseObject.responseText);
                    if(resultInfo.status)
                    {
                        showInfoMessageProc(resultInfo.message, function(btn_pressed){
                            //if (btn_pressed == 'ok') {
                                window.location.href = resultInfo.redirect;
                            //}
                        });
                    }
                    else
                    {
                        if (typeof(resultInfo.captcha) != 'undefined') {
                            $('#captcha-image').attr('src', resultInfo.captcha);
                            //console.log(resultInfo.captcha);
                            Ext.getCmp('captcha').setValue('');
                        }
                        Ext.getCmp('password').setValue('');
                        Ext.getCmp('conf_password').setValue('');
                            showWarningMessage(resultInfo.message);
                        }
                    },
                    failure: function(){
                        Ext.MessageBox.hide();
                        showErrorMessage(langlines.main_server_error);                                                        
                    },
                    params: dataSend
                });
        }
        else
        {
            showErrorMessage(langlines.main_please_fill_all_fields);                                
        }
	});
	
	$('#plan_type').val(plan_name);
    $('#pay_opt').val('Monthly');
	if (plan_name == 'freemium') {
        $('#payment_details').hide();
        $('#express_checkout_box').hide();
        $('#payment_prop').hide();
        $('#pay_opt').val('Monthly');
	} else if (plan_name == '') {
		$('#money_calculate_holder').hide();
	} else {
        if      (plan_name == 'premium'   ) {result = langlines.user_plan_2_monthly_description;}
        else if (plan_name == 'enterprise') {result = langlines.user_plan_3_monthly_description;}
        else    {result = '';}
        if (result != '') {
            $('#money_calculate').text(result);
            $('#money_calculate_holder').show();
        } else {
            $('#money_calculate_holder').hide();
        }
    }
	// IF IS BETA
	$('#payment_details').hide();
    $('#express_checkout_box').hide();
    $('#payment_prop').hide();
    
    
	Ext.select('div#frm1').first().enableDisplayMode().hide();
});
