/**
 * create purchase another button
 *
 * @param array userdata
 * @retun string html output
 */
function mgm_get_purchase_another_subscription_button($args = array())
{
    global $wpdb;
    //ceck settings
    $settings = mgm_get_class('system')->get_setting();
    // check
    if (!isset($settings['enable_multiple_level_purchase']) || isset($settings['enable_multiple_level_purchase']) && !bool_from_yn($settings['enable_multiple_level_purchase'])) {
        return;
    }
    // current user
    $user = wp_get_current_user();
    // validate
    if (!$user->ID) {
        // query string
        $user = mgm_get_user_from_querystring();
    }
    // validate
    if (!$user->ID) {
        return __('No such user', 'mgm');
    }
    // userdata
    $username = $user->user_login;
    $mgm_home = get_option('siteurl');
    $member = mgm_get_member($user->ID);
    $system_obj = mgm_get_class('system');
    $membership_type = mgm_get_user_membership_type($user->ID, 'code');
    $packs_obj = mgm_get_class('subscription_packs');
    $packs = $packs_obj->get_packs('upgrade');
    $duration_str = $packs_obj->duration_str;
    $trial_taken = $member->trial_taken;
    // pack_ids
    $pack_ids = mgm_get_members_packids($member);
    $pack_membership_types = mgm_get_subscribed_membershiptypes($user->ID, $member);
    // query_arg
    $form_action = mgm_get_custom_url('transactions', false, array('action' => 'purchase_another', 'username' => $username));
    //issue 1009
    if (isset($settings['membership_details_url'])) {
        $membership_details_url = $settings['membership_details_url'];
    } else {
        $membership_details_url = get_admin_url() . 'profile.php?page=mgm/profile';
    }
    // cancel
    $cancel_url = $membership_details_url;
    // $cancel_url = mgm_get_custom_url('membership_details');
    // active modules
    $a_payment_modules = $system_obj->get_active_modules('payment');
    // 	selected_subscription
    $selected_subs = mgm_get_selected_subscription($args);
    // second step, after post
    if (isset($_POST['submit'])) {
        // verify selected
        if (!isset($_POST['subs_opt'])) {
            // die
            return sprintf(__('Package not selected, <a href="%s">go back</a>.', 'mgm'), $_POST['form_action']);
            exit;
        }
        // get subs data
        $subs_opt_pack = mgm_decode_package($_POST['subs_opt']);
        extract($subs_opt_pack);
        // check
        $valid = false;
        // loop packs
        foreach ($packs as $pack) {
            // check
            //check pack id as well: issue#: 580
            if ($pack['cost'] == $cost && $pack['duration'] == $duration && $pack['duration_type'] == $duration_type && $membership_type == $pack['membership_type'] && $pack_id == $pack['id']) {
                $valid = true;
                break;
            }
        }
        // error
        if (!$valid) {
            return __('Invalid data passed', 'mgm');
            exit;
        }
        // get object
        $member = new mgm_member($user->ID);
        $temp_membership = $member->_default_fields();
        $temp_membership['membership_type'] = $membership_type;
        $temp_membership['pack_id'] = $pack_id;
        //issue #860
        //if (isset($_POST['mgm_upgrade_field']['autoresponder']) && ($_POST['mgm_upgrade_field']['autoresponder'])=='Y') {
        if (isset($_POST['mgm_upgrade_field']['autoresponder']) && substr($_POST['mgm_upgrade_field']['autoresponder'], 0, 1) == 'Y') {
            $temp_membership['subscribed'] = 'Y';
            $temp_membership['autoresponder'] = $system_obj->active_modules['autoresponder'];
        }
        //issue #1236
        if (isset($_POST['mgm_upgrade_field']['coupon']) && !empty($_POST['mgm_upgrade_field']['coupon'])) {
            //issue #1250 - Coupon validation
            if (!empty($_POST['form_action'])) {
                // check if its a valid coupon
                if (!($coupon = mgm_get_coupon_data($_POST['mgm_upgrade_field']['coupon']))) {
                    //redirect back to the form
                    $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'error_field_value' => $_POST['mgm_upgrade_field']['coupon']);
                    $redirect = add_query_arg($q_arg, $_POST['form_action']);
                    // redirect
                    mgm_redirect($redirect);
                    exit;
                } else {
                    // membership type check
                    // get subs
                    if ($subs_pack = mgm_decode_package(mgm_post_var('subs_opt'))) {
                        // values
                        $coupon_values = mgm_get_coupon_values(NULL, $coupon['value'], true);
                        // check
                        if (isset($coupon_values['new_membership_type']) && $coupon_values['new_membership_type'] != $subs_pack['membership_type']) {
                            $new_membership_type = mgm_get_membership_type_name($coupon_values['new_membership_type']);
                            $q_arg = array('error_field' => 'Coupon', 'error_type' => 'invalid', 'membership_type' => $coupon_values['new_membership_type'], 'error_field_value' => $_POST['mgm_upgrade_field']['coupon']);
                            $redirect = add_query_arg($q_arg, $_POST['form_action']);
                            // redirect
                            mgm_redirect($redirect);
                            exit;
                        }
                    }
                }
            }
        }
        //inserted an incomplete entry for the selected subscription type
        mgm_save_another_membership_fields($temp_membership, $user->ID);
        // save coupon fields and update member object
        $member = mgm_save_partial_fields_purchase_more($user->ID, $membership_type, $cost);
        // coupon
        $purchase_another_coupon = false;
        // array
        if (isset($member->upgrade)) {
            if (is_array($member->upgrade) && isset($member->upgrade['coupon']['id'])) {
                $purchase_another_coupon = $member->upgrade['coupon'];
            } elseif (is_object($member->upgrade) && isset($member->upgrade->coupon->id)) {
                $purchase_another_coupon = mgm_object2array($member->upgrade->coupon);
            }
            // coupon
            mgm_get_purchase_another_coupon_pack($purchase_another_coupon, $pack);
        }
        //save custom fields -issue #1285
        if (isset($_POST['mgm_upgrade_field']) && !empty($_POST['mgm_upgrade_field'])) {
            //member
            $cf_member = mgm_get_member($user->ID);
            //upgrade custom fileds
            $cfu_fileds = mgm_get_class('member_custom_fields')->get_fields_where(array('display' => array('on_multiple_membership_level_purchase' => true)));
            //loop fields
            foreach ($cfu_fileds as $cf_filed) {
                //skip coupon and autoresponder
                if (in_array($cf_filed['name'], array('coupon', 'autoresponder'))) {
                    continue;
                }
                //check
                if (isset($_POST['mgm_upgrade_field'][$cf_filed['name']])) {
                    // check upgrae and required
                    if ((bool) $cf_filed['attributes']['required'] === true) {
                        if (empty($_POST['mgm_upgrade_field'][$cf_filed['name']])) {
                            //redirect back to the form
                            $q_arg = array('error_field' => $cf_filed['label'], 'error_type' => 'empty', 'error_field_value' => $_POST['mgm_upgrade_field'][$cf_filed['name']]);
                            $redirect = add_query_arg($q_arg, $_POST['form_action']);
                            mgm_redirect($redirect);
                            exit;
                        }
                    }
                    //appending custom fields
                    if (isset($cf_member->custom_fields->{$cf_filed}['name'])) {
                        $cf_member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                    } else {
                        $cf_member->custom_fields->{$cf_filed}['name'] = $_POST['mgm_upgrade_field'][$cf_filed['name']];
                    }
                }
            }
            $cf_member->save();
        }
        // start html
        $html = '<div>';
        // free
        if (($pack['cost'] == 0 || $membership_type == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->is_enabled()) {
            $html .= sprintf('<div>%s - %s</div>', __('Create a free account ', 'mgm'), ucwords($membership_type));
            $module = 'mgm_free';
            // payments url
            $payments_url = mgm_get_custom_url('transactions');
            // if tril module selected and cost is 0 and free moduleis not active
            if ($membership_type == 'trial') {
                if (in_array('mgm_trial', $a_payment_modules)) {
                    $module = 'mgm_trial';
                }
            }
            //Purchase Another Membership Level problem : issue #: 752
            $redirect = add_query_arg(array('method' => 'payment_return', 'module' => $module, 'custom' => $user->ID . '_' . $duration . '_' . $duration_type . '_' . $pack_id . '_Y', 'redirector' => $redirector), $payments_url);
            // redirect
            if (!headers_sent()) {
                @header('location: ' . $redirect);
                exit;
            }
            // js redirect
            $html .= sprintf('<script type="text/javascript">window.location = "%s";</script><div>%s</div>', $redirect, $packs_obj->get_pack_desc($pack));
        } else {
            $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $packs_obj->get_pack_desc($pack));
            // coupon
            if (isset($purchase_another_coupon['id'])) {
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', sprintf(__('Using Coupon "%s" - %s', 'mgm'), $purchase_another_coupon['name'], $purchase_another_coupon['description']));
            }
            $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', __('Please Select from Available Payment Gateways', 'mgm'));
        }
        //bypass if payment gateway field is selected -issue #1764
        if ((double) $pack['cost'] > 0 && isset($_POST['mgm_payment_gateways']) && !empty($_POST['mgm_payment_gateways'])) {
            //init
            $tran_id = 0;
            if (!$tran_id) {
                $tran_id = mgm_add_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
            }
            // module
            $mod_obj = mgm_get_module($_POST['mgm_payment_gateways'], 'payment');
            // module end point
            $redirect = $mod_obj->_get_endpoint('html_redirect', false);
            // encode id:
            //encode transaction id
            $encode_tran_id = mgm_encode_id($tran_id);
            //args
            $redirect = add_query_arg(array('tran_id' => $encode_tran_id), $redirect);
            // do the redirect to payment
            mgm_redirect($redirect);
        }
        // init
        $payment_modules = array();
        // when active
        if ($a_payment_modules) {
            // loop
            foreach ($a_payment_modules as $payment_module) {
                // not trial
                if (in_array($payment_module, array('mgm_free', 'mgm_trial'))) {
                    continue;
                }
                //consider only the modules assigned to pack
                if (isset($pack['modules']) && !in_array($payment_module, (array) $pack['modules'])) {
                    continue;
                }
                // store
                $payment_modules[] = $payment_module;
            }
        }
        // loop payment mods if not free
        if (count($payment_modules) && $cost) {
            // transaction
            $tran_id = 0;
            // loop
            foreach ($payment_modules as $module) {
                // module
                $mod_obj = mgm_get_module($module, 'payment');
                // create transaction
                // if(!$tran_id) $tran_id = $mod_obj->_create_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
                if (!$tran_id) {
                    $tran_id = mgm_add_transaction($pack, array('is_another_membership_purchase' => true, 'user_id' => $user->ID));
                }
                // button
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', $mod_obj->get_button_subscribe(array('pack' => $pack, 'tran_id' => $tran_id)));
            }
        } else {
            if ($cost) {
                $html .= sprintf('<div class="mgm_get_subs_btn">%s</div>', __('There are no payment gateways available at this time.', 'mgm'));
            }
        }
        // html
        $html .= '</div>';
    } else {
        // first step show upgrade options
        // html
        $html = sprintf('<p class="message register">%s</p>', __('Please Select from Available Membership Packages', 'mgm'));
        // upgrade_packages
        $upgrade_packages = '';
        // pack to modules
        $pack_modules = array();
        // loop
        foreach ($packs as $pack) {
            // default
            $checked = '';
            // skip already purchased packs
            if (in_array($pack['id'], $pack_ids)) {
                continue;
            }
            //skip same membership level subscriptions
            if (in_array($pack['membership_type'], $pack_membership_types)) {
                continue;
            }
            // do not show trial or free as upgradre
            if ($pack['membership_type'] == 'trial' || $pack['membership_type'] == 'free') {
                continue;
            }
            // reset
            $checked = mgm_select_subscription($pack, $selected_subs);
            // skip other when a package sent as selected
            if ($selected_subs !== false) {
                if (empty($checked)) {
                    continue;
                }
            }
            // checked
            if (!$checked) {
                $checked = (int) $pack['default'] == 1 ? ' checked="checked"' : '';
            }
            // duration
            if ($pack['duration'] == 1) {
                $dur_str = rtrim($duration_str[$pack['duration_type']], 's');
            } else {
                $dur_str = $duration_str[$pack['duration_type']];
            }
            $css_group = mgm_get_css_group();
            // encode pack
            $subs_opt_enc = mgm_encode_package($pack);
            // set
            $pack_modules[$subs_opt_enc] = $pack['modules'];
            //issue #867
            if ($css_group != 'none') {
                //expand this if needed
                $css_link_format = '<link rel="stylesheet" href="%s" type="text/css" media="all" />';
                $css_file = MGM_ASSETS_URL . 'css/' . $css_group . '/mgm.form.fields.css';
                $upgrade_packages .= sprintf($css_link_format, $css_file);
            }
            // free
            if (($pack['cost'] == 0 || strtolower($pack['membership_type']) == 'free') && in_array('mgm_free', $a_payment_modules) && mgm_get_module('mgm_free')->enabled == 'Y') {
                // input
                $input = sprintf('<input type="radio" %s class="checkbox" name="subs_opt" value="%s" rel="mgm_subscription_options"/>', $checked, $subs_opt_enc);
                // html
                $upgrade_packages .= '  
							<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
								<div class="mgm_subs_option ' . $pack['membership_type'] . '">
									' . $input . '
								</div>
								<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
									' . $packs_obj->get_pack_desc($pack) . '
								</div>
								 <div class="clearfix"></div>
								 <div class="mgm_subs_desc ' . $pack['membership_type'] . '">
									' . mgm_stripslashes_deep($pack['description']) . '
								 </div>
							</div>';
            } else {
                // input
                $input = sprintf('<input type="radio" %s class="checkbox" name="subs_opt" value="%s" rel="mgm_subscription_options"/>', $checked, $subs_opt_enc);
                // html
                $upgrade_packages .= '  
							<div class="mgm_subs_wrapper ' . $pack['membership_type'] . '">
								<div class="mgm_subs_option ' . $pack['membership_type'] . '">
									' . $input . '
								</div>
								<div class="mgm_subs_pack_desc ' . $pack['membership_type'] . '">
									' . $packs_obj->get_pack_desc($pack) . '
								</div>
								 <div class="clearfix"></div>
								 <div class="mgm_subs_desc ' . $pack['membership_type'] . '">
									' . mgm_stripslashes_deep($pack['description']) . '
								 </div>
							</div>';
            }
        }
        // add pack_modules as json data, may consider jquery data later
        if (!empty($pack_modules)) {
            $html .= sprintf('<script language="javascript">var mgm_pack_modules = %s</script>', json_encode($pack_modules));
        }
        // show error
        if (!$upgrade_packages) {
            // html
            $html .= '<div class="mgm_subs_wrapper">
						<div class="mgm_subs_pack_desc">
							' . __('Sorry, no packages available.', 'mgm') . '
						</div>
					 </div>
					 <p>						
						<input type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '" class="button-primary" />&nbsp;					
					 </p>';
        } else {
            /*			$error_field = mgm_request_var('error_field'); 
            			if(!empty($error_field)) {
            				$errors = new WP_Error();
            				switch (mgm_request_var('error_type')) {
            					case 'empty':
            						$error_string = 'You must provide a ';
            						break;
            					case 'invalid':
            						$error_string = 'Invalid ';
            						break;	
            				}				
            				//issue #703
            				$errors->add( $error_field, __( '<strong>ERROR</strong>: '.$error_string, 'mgm' ).$error_field );
            				$html .= mgm_set_errors($errors, true);					
            			}*/
            // check errors if any:
            $html .= mgm_subscription_purchase_errors();
            // form
            $html .= '<form action="' . $form_action . '" method="post" class="mgm_form"><div class="mgm_get_pack_form_container">';
            $html .= '<input type="hidden" name="form_action" value="' . $form_action . '" />';
            $html .= $upgrade_packages;
            //issue #1285
            $html .= mgm_get_custom_fields($user->ID, array('on_multiple_membership_level_purchase' => true), 'mgm_upgrade_field');
            // html
            $html .= '<input type="hidden" name="ref" value="' . md5($member->amount . '_' . $member->duration . '_' . $member->duration_type . '_' . $member->membership_type) . '" />';
            // set
            $html .= '<p>						
						<input class="button" type="submit" name="submit" value="' . __('Next', 'mgm') . '" />&nbsp;&nbsp;
						<input class="button" type="button" name="cancel" onclick="window.location=\'' . $cancel_url . '\'" value="' . __('Cancel', 'mgm') . '"/>&nbsp;					
					  </p>';
            // html
            $html .= '</div></form>';
        }
    }
    // return
    return $html;
}
/**
 * generate custom register page default fields layout
 * 
 * @uses mgm filter "mgm_generate_register_form_template"
 *
 * @param array $form_params
 * @return sting $form_template
 * @since 2.6
 */
function mgm_generate_register_form_template($form_params)
{
    // get mgm_system
    $system_obj = mgm_get_class('system');
    // no custom fields
    $hide_custom_fields = $system_obj->get_setting('hide_custom_fields');
    // extract
    extract($form_params);
    // form_template
    $form_template = '';
    $paid_modules = array();
    $arr_modulestoskip = array('mgm_free', 'mgm_trial');
    $obj_packs = mgm_get_class('subscription_packs');
    // rewrite args if suplied through url
    if ($args_package = mgm_request_var('package', '', true)) {
        $args['package'] = base64_decode($args_package);
    }
    // if single package
    if (isset($args['package'])) {
        if (count(explode("#", $args['package'])) == 1) {
            $pack_list_data = explode("#", $args['package']);
            $pack_list_data[1] = false;
        } else {
            $pack_list_data = explode("#", $args['package']);
        }
        list($mtype, $packid) = $pack_list_data;
        $mtype = mgm_get_class('membership_types')->get_type_code($mtype);
        if ($packid) {
            $packs = array(0 => $obj_packs->get_pack($packid));
        } else {
            /*			$reg_packs = $packs = $obj_packs->get_packs('register');
            			$packs = array();
            */
            //issue #1398
            $packs = array();
            // selected subscription
            $selected_subs = mgm_get_selected_subscription($args);
            // packs
            $reg_packs = $packs = $obj_packs->get_packs('register', true, $selected_subs);
            foreach ($reg_packs as $rp) {
                if ($rp['membership_type'] == $mtype) {
                    $packs[] = $rp;
                }
            }
        }
    } else {
        $packs = $obj_packs->get_packs('register');
    }
    // log
    // mgm_pr($cf_register_page);
    // loop to create form template
    foreach ($cf_register_page as $field) {
        // skip custom fields by settings call
        if ($hide_custom_fields == 'Y' || $hide_custom_fields == 'W' && $wordpres_form || $hide_custom_fields == 'C' && !$wordpres_form) {
            // some fields required irespective of settings
            if (!in_array($field['name'], array('subscription_options', 'payment_gateways'))) {
                continue;
            }
        }
        // skip username
        if ($field['name'] == 'username' && bool_from_yn($system_obj->get_setting('enable_email_as_username'))) {
            continue;
        }
        // gateway
        if ($field['name'] == 'payment_gateways') {
            $total_amount = 0;
            foreach ($packs as $pack) {
                $total_amount += $pack['cost'];
                //check enabled modules
                if (!empty($pack['modules'])) {
                    foreach ($pack['modules'] as $mod) {
                        if (!in_array($mod, $arr_modulestoskip)) {
                            $paid_modules[$mod] = true;
                        }
                    }
                }
            }
            //Skip payment gateways if total amount is 0
            if (!$total_amount) {
                continue;
            }
        }
        // field wrapper place holder
        $wrapper_ph = sprintf('[user_field_wrapper_%s]', $field['name']);
        // field label
        // if hiddden field, do not show label
        if ($field['type'] == 'hidden') {
            $label_ph = '';
        } else {
            //skip label if only one payment module is enabled, The module will be internally processed in this case
            $label_ph = count($paid_modules) == 1 && $field['name'] == 'payment_gateways' ? '' : sprintf('[user_field_label_%s]', $field['name']);
        }
        // field/html element
        $element_ph = sprintf('[user_field_element_%s]', $field['name']);
        // template for autoresponder// TODO check template for each individual field in theme folder
        if ($field['name'] == 'autoresponder' || $field['name'] == 'show_public_profile') {
            // template
            $form_row_template_ar = $system_obj->get_template('register_form_row_autoresponder_template');
            // set element place holders
            $form_template .= str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wrapper_ph, $label_ph, $element_ph), $form_row_template_ar);
        } else {
            // set element place holders
            $form_template .= str_replace(array('[user_field_wrapper]', '[user_field_label]', '[user_field_element]'), array($wrapper_ph, $label_ph, $element_ph), $form_row_template);
        }
    }
    //issue #1510
    if (defined('BP_VERSION') && BP_VERSION == '1.8') {
        $clearboth = '<p style="clear:both;"></p>';
        $f_template = $clearboth;
        $f_template .= $form_template;
        // return
        return $f_template;
    } else {
        // return
        return $form_template;
    }
}
    /**
     * Callback for payment_gateways field
     * prints all active modules, javascript callback and json data shows per pack 
     * or filtered 
     *
     * @param array $field
     * @param string $name
     * @param string $value
     * @return string
     */
    function field_payment_gateways_callback($field, $name, $value)
    {
        // display as
        $dispaly_as_selectbox = $this->_get_subscription_options_as();
        //check subscription options custom_field is enabled:
        $continue = false;
        // cf
        $obj_customfields = mgm_get_class('member_custom_fields');
        // subo
        $arr_sub_options = $obj_customfields->get_field_by_name('subscription_options');
        // check
        if (isset($arr_sub_options['id']) && !empty($obj_customfields->sort_orders) && in_array($arr_sub_options['id'], $obj_customfields->sort_orders)) {
            $continue = true;
        }
        // return
        if (!$continue) {
            return '';
        }
        $system_obj = mgm_get_class('system');
        // args
        $args = $this->get_config('args', array());
        // selected_subscription
        $selected_subs = mgm_get_selected_subscription($args);
        // get active modules
        $a_payment_modules = $system_obj->get_active_modules('payment');
        /* @todo deprecate load here since gateways are loaded for post purchase also
        		// get modules for packs:
        		$allpacks = mgm_get_class('subscription_packs')->get_packs();		
        		// init
        		$pack_modules = array();		
        		// loop
        		foreach ($allpacks as $allp) {
        			// reset
        			$include = mgm_select_subscription($allp,$selected_subs);						
        			// skip other when a package sent as selected
        			if($selected_subs !== false){
        				if(empty($include)) continue;
        			}
        			//issue #1532
        			if(is_array($allp['modules'])){
        				$pack_modules = array_merge($pack_modules,$allp['modules']);
        			}
        		}
        		// pack
        		$pack_modules = array_unique($pack_modules);
        		
        		mgm_pr($pack_modules);*/
        // payment modules
        $payment_modules = array();
        // loop
        if (!empty($a_payment_modules)) {
            // loop
            foreach ($a_payment_modules as $payment_module) {
                // not trial
                if (in_array($payment_module, array('mgm_free', 'mgm_trial'))) {
                    continue;
                }
                // included modules
                // if( ! in_array($payment_module, $pack_modules) ) continue;
                // store
                $payment_modules[] = $payment_module;
            }
        }
        // make unique
        $payment_modules = apply_filters('mgm_payment_gateways_as_custom_field', array_unique($payment_modules));
        // check count
        $module_count = count($payment_modules);
        // one active
        $hide_div = $module_count === 1 ? 'style="display:none;"' : '';
        // NOTE: uncomment the below line to enable module display even if only one exists
        // $hide_div = "";
        // NOTE: do not change the id: mgm_payment_gateways_container
        $html = sprintf('<div id="mgm_payment_gateways_container" class="mgm_payment_wrapper" %s >', $hide_div);
        //loop through payment modules:
        if ($module_count == 0) {
            $html .= sprintf('<div>%s</div>', __('No active payment module', 'mgm'));
        } else {
            //print each module:
            foreach ($payment_modules as $payment_module) {
                //checked: if(selected/only one gateway exists)
                if (isset($_POST['mgm_payment_gateways'])) {
                    $checked = $payment_module == $_POST['mgm_payment_gateways'] ? 'checked="true"' : '';
                } else {
                    $checked = !empty($value) && $value == $field['value'] || $module_count === 1 ? 'checked="true"' : '';
                }
                // get obj
                $mod_obj = mgm_get_module($payment_module, 'payment');
                // html
                $img_url = mgm_site_url($mod_obj->logo);
                // desc
                $description = mgm_stripslashes_deep($mod_obj->description);
                //module description
                $html .= sprintf('<div id="%s_container" class="mgm_payment_opt_wrapper" %s>
						  	<input type="radio" %s class="checkbox" name="mgm_payment_gateways" value="%s" alt="%s" />
						 	<img class="mgm_payment_opt_customfield_image" src="%s" alt="%s" />
						  	<div class="mgm_paymod_description">%s</div>
						 </div>', $mod_obj->code, $hide_div, $checked, $mod_obj->code, $mod_obj->name, $img_url, $mod_obj->name, $description);
            }
            // scripts required for pack buttons:
            // $packs_obj = mgm_get_class('subscription_packs');
            // packs
            // $packs = $packs_obj->get_packs('register');
            // $lf = "\n";
            //script to show/hide appicable module buttons
            $html .= '<script type="text/javascript">jQuery(document).ready(function() {' . PHP_EOL;
            // bind as needed
            if ($dispaly_as_selectbox) {
                $html .= 'jQuery("select[rel=\'mgm_subscription_options\']").bind("change", function(){ mgm_select_pack_modules("select"); }).change();' . PHP_EOL;
            } else {
                $html .= 'jQuery(":input[rel=\'mgm_subscription_options\']").bind("click", function(){ mgm_select_pack_modules("radio"); });' . PHP_EOL;
                $html .= 'mgm_select_pack_modules("' . ($dispaly_as_selectbox ? 'select' : 'radio') . '");' . PHP_EOL;
                // @todo consider SELECT
            }
            // end
            $html .= '});</script>' . PHP_EOL;
        }
        // end
        $html .= '</div>';
        // return
        return $html;
    }
function mgm_fb_subscription_options_callback($field, $name, $value)
{
    $options_arr = array();
    // get object
    $packs_obj = mgm_get_class('subscription_packs');
    // get mgm_system
    $system_obj = mgm_get_class('system');
    // args
    $args = array();
    // selected subscription
    $selected_subs = mgm_get_selected_subscription($args);
    // packs
    $packs = $packs_obj->get_packs('register', true, $selected_subs);
    // total
    $total_amount = 0;
    // total calc
    foreach ($packs as $pack) {
        $total_amount += $pack['cost'];
    }
    // active payment modules
    $a_payment_modules = $system_obj->get_active_modules('payment');
    // active module
    if (count($a_payment_modules) == 0 && $total_amount > 0) {
        return sprintf('<p>%s</p>', __('There are no payment gateways active. Please contact the administrator.', 'mgm'));
    } else {
        // payment_module
        $payment_modules = array();
        // loop
        foreach ($a_payment_modules as $payment_module) {
            // skip free/trial
            if (in_array($payment_module, array('mgm_free', 'mgm_trial'))) {
                continue;
            }
            // increment
            $payment_modules[] = $payment_module;
        }
        // loop packs
        foreach ($packs as $pack) {
            // reset
            $checked = mgm_select_subscription($pack, $selected_subs);
            // skip other when a package sent as selected
            if ($selected_subs !== false) {
                if (empty($checked)) {
                    continue;
                }
            }
            // subs encrypted
            $subs_enc = mgm_encode_package($pack);
            if ((strtolower($pack['membership_type']) == 'free' || $pack['cost'] == 0 && mgm_get_module('mgm_free')->enabled == 'Y') && in_array('mgm_free', $a_payment_modules)) {
                $options_arr[$subs_enc] = trim(mgm_stripslashes_deep($packs_obj->get_pack_desc($pack)));
                // trial
            } elseif (strtolower($pack['membership_type']) == 'trial' && in_array('mgm_trial', $a_payment_modules)) {
                $options_arr[$subs_enc] = trim(mgm_stripslashes_deep($packs_obj->get_pack_desc($pack)));
            } else {
                // paid subscription active
                if (count($payment_modules)) {
                    // check cost and hide false
                    if ($pack['cost']) {
                        $options_arr[$subs_enc] = trim(mgm_stripslashes_deep($packs_obj->get_pack_desc($pack)));
                    }
                    // end if
                } elseif ($pack['cost'] > 0) {
                    // set message
                    //$html .= sprintf('<div class="message" style="margin:10px 0px; overflow: auto;color:red;font-weight:bold">%s</div>',__('Please enable a payment module to allow ' . mgm_stripslashes_deep($packs_obj->get_pack_desc($pack)) ,'mgm'));
                }
                // end paid
            }
        }
        // end pack loop
    }
    // return
    return json_encode($options_arr);
}