<?php
error_reporting(E_ALL & ~E_NOTICE);
define('THIS_SCRIPT', 'ugmarkup');
require_once('./global.php');
require_once(DIR . '/includes/adminfunctions_template.php');

if (!can_administer('canadminpermissions')){
    print_cp_no_permission();
}

if(!class_exists('UGMarkup')){
    require(DIR . '/ugmarkup/includes/class_ugmarkup.php');
    UGMarkup::init($vbulletin);
}

?>
<script type="text/javascript" src="../clientscript/vbulletin_cpcolorpicker.js?v=<?php echo SIMPLE_VERSION; ?>"></script>
<script src="<?php echo UGMarkup::$JSPATH . '/jquery-latest.min.js' ?>" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="<?php echo UGMarkup::$CSSPATH; ?>/msdropdown/dd.css" />
<script src="<?php echo UGMarkup::$JSPATH . '/jquery.dd.min.js' ?>" type="text/javascript"></script>
<style type="text/css">
    .imageSelectorImage{
        max-width: <?php echo UGMarkup::setting('icon_maxwidth') ?>;
        max-height: <?php echo UGMarkup::setting('icon_maxheight') ?>;
    }
    .iconPath{
        font-weight: bold;
    }
    .iconPath a{
        color: #00009D;
    }
    .iconPath a:hover{
        color: #00009D;
    }
    .iconPath a:visited{
        color: #00009D;
    }
    .iconPathInvalid{
        background-color: red;
    }
</style>

<?php
$colorPicker = construct_color_picker(11);
global $db;

if(empty($_REQUEST['do'])) $_REQUEST['do'] = 'main';
print_cp_header('Usergroup Markup Customizer');

if($_REQUEST['do'] == 'update')
{
    $gpcfields = array(
        'bold'     => TYPE_ARRAY,
        'color'    => TYPE_ARRAY,
        'image'    => TYPE_ARRAY,
        'imagedir' => TYPE_ARRAY,
        'rainbow'  => TYPE_ARRAY,
        'custom'   => TYPE_ARRAY
    );
    $vbulletin->input->clean_array_gpc('p', $gpcfields);
    foreach ($gpcfields as $key => $value) {
       $$key =& $vbulletin->GPC[$key];
    }
    foreach ($bold as $index => $value) {
        $index = intval($index);
        $db->query_write("
            UPDATE " .TABLE_PREFIX. "usergroup
            SET
                ugmarkup_bold     = ".$db->sql_prepare($bold[$index] == 1 ? 1 : 0).",
                ugmarkup_color    = ".($color[$index] ? $db->sql_prepare($color[$index]) : 'NULL').",
                ugmarkup_image    = ".($image[$index] != -1 ? $db->sql_prepare($image[$index]) : 'NULL').",
                ugmarkup_imagedir = ".$db->sql_prepare($imagedir[$index] == 1 ? 0 : 1).",
                ugmarkup_rainbow  = ".$db->sql_prepare($rainbow[$index] == 1 ? 1 : 0).",
                ugmarkup_custom   = ".($custom[$index] ? $db->sql_prepare($custom[$index]) : 'NULL')."
            WHERE usergroupid = '$index'
        ");
    }
    build_forum_permissions();
    print_cp_message("Usergroup Markup Successfully Updated",'ugmarkup.php');
}


if($_REQUEST['do'] == 'main')
{
    print_form_header('ugmarkup', 'update');
    $header_rows = array(
        'Usergroup',
         'Bold',
         'Color<dfn>Note: Overwrites "Custom CSS" color rules/settings</dfn>',
         'Icon',
         'Icon Position',
         'Rainbow<dfn>If enabled, overwrites all color rules/settings</dfn>',
         'Additional/Custom CSS<dfn>Seperate each rule with a new line</dfn>'
    );
    $header_rows_count = count($header_rows);
    $click_here = ' - <a href="options.php?do=options&dogroup=ugmarkup_settings" target="_blank">Settings</a>';
    if((DIR . '/') == UGMarkup::$FULLPATH OR !file_exists(UGMarkup::$FULLPATH)){
        print_description_row('Invalid icon path: /'.UGMarkup::$IMAGEPATH . $click_here,
            false, $header_rows_count, 'iconPath iconPathInvalid', 'center');
    }
    else{
        print_description_row('Using icons from: /'.UGMarkup::$IMAGEPATH . $click_here, false, $header_rows_count, 'iconPath', 'center');
    }

    print_table_break();

    print_table_header('Settings', $header_rows_count);
    print_cells_row($header_rows, 1, '', 1);

    $ugs = $db->query_read("
        SELECT usergroupid, title, ugmarkup_bold, ugmarkup_color, ugmarkup_image, ugmarkup_imagedir, ugmarkup_rainbow, ugmarkup_custom
        FROM " .TABLE_PREFIX. "usergroup
        ORDER BY title
    ");

    while ($ug = $db->fetch_array($ugs)) {
        $row = array();
        $row[] = (UGMarkup::setting('show_usergroup_preview') ? UGMarkup::processText($ug['title'], $ug['usergroupid']) : $ug['title']) .
            (UGMarkup::setting('show_usergroupid') ? " (id:$ug[usergroupid])" : '');
        $row[] = print_yes_no_cell("bold[$ug[usergroupid]]", $ug['usergroupid'], $ug['ugmarkup_bold']);
        $row[] = print_color_cell($ug['usergroupid'], $ug['ugmarkup_color']);
        $row[] = print_image_chooser($ug['usergroupid'], $ug['ugmarkup_image']);
        $row[] = print_yes_no_cell("imagedir[$ug[usergroupid]]", $ug['usergroupid'], !$ug['ugmarkup_imagedir'], 'Left', 'Right');
        $row[] = print_yes_no_cell("rainbow[$ug[usergroupid]]", $ug['usergroupid'], $ug['ugmarkup_rainbow']);
        $row[] = print_textarea_cell('custom', $ug['usergroupid'], $ug['ugmarkup_custom']);
        print_cells_row($row, 0, '', 1);
    }
    $db->free_result($ugs);
    print_submit_row('Update', '_default_', $header_rows_count);
        echo $colorPicker;
    ?>
    <script type="text/javascript">
    <!--

    var bburl = "<?php echo $vbulletin->options['bburl']; ?>/";
    var cpstylefolder = "<?php echo $vbulletin->options['cpstylefolder']; ?>";
    var numColors = <?php echo intval($numcolors); ?>;
    var colorPickerWidth = <?php echo intval($colorPickerWidth); ?>;
    var colorPickerType = <?php echo intval($colorPickerType); ?>;

    init_color_preview();

    //-->
    </script>

    <script type="text/javascript">
        $('.imageSelector').msDropDown({visibleRows:15});
        setTimeout(function(){
            // $(document).height() = 708;
        }, 0);

    </script>
    <?php
}

print_cp_footer();

function print_image_chooser($id, $current)
{
    global $vbulletin;
    static $images_sorted = array();
    if(empty($images_sorted)){
        $images = glob(UGMarkup::$FULLPATH . "/*.{jpg,png,gif}", GLOB_BRACE);
        foreach ($images as $value) {
            $parts = pathinfo($value);
            $images_sorted[$parts['filename']] = $parts['basename'];
        }
        natsort($images_sorted);
    }

    $html =
    '<select name="image['.$id.']" class="imageSelector" style="width:200px;">
    <option value="-1" data-image="">None</option>';
    foreach ($images_sorted as $key => $value) {
        $selected = $value == $current ? ' selected="selected"' : '';
        $key = ucwords(str_replace(array('_','-'), ' ', $key));
        $html .= '<option value="'.$value.'" data-image="'.UGMarkup::$URLPATH . "/$value\" data-imagecss=\"imageSelectorImage\"".$selected.'>'.$key.'</option>';
    }
    $html .= '</select>';
    return $html;
}

function print_textarea_cell($name, $id, $value)
{
    return '<textarea rows="4" cols="50" name="'.$name."[$id]".'">'.$value.'</textarea>';
}

function print_yes_no_cell($name, $uniqueid, $value, $yes = '', $no = '')
{
    global $vbulletin, $vbphrase;
    return "<div id=\"ctrl_$name\" class=\"smallfont\" style=\"white-space:nowrap\">
        <label for=\"rb_1_{$name}_$uniqueid\"><input type=\"radio\" name=\"$name\" id=\"rb_1_{$name}_$uniqueid\" value=\"" . (($name == 'user[pmpopup]' AND $value == 2) ? 2 : 1) . "\" tabindex=\"1\"$onclick" . iif($vbulletin->debug, " title=\"name=&quot;$name&quot; value=&quot;1&quot;\"") . iif($value == 1 OR ($name == 'user[pmpopup]' AND $value == 2), ' checked="checked"') . " />". ($yes ? $yes : $vbphrase['yes']) . iif(vB_Template_Runtime::fetchStyleVar('textdirection') == 'rtl', "&rlm;") . "</label>
        <label for=\"rb_0_{$name}_$uniqueid\"><input type=\"radio\" name=\"$name\" id=\"rb_0_{$name}_$uniqueid\" value=\"0\" tabindex=\"1\"$onclick" . iif($vbulletin->debug, " title=\"name=&quot;$name&quot; value=&quot;0&quot;\"") . iif($value == 0, ' checked="checked"') . " />". ($no ? $no : $vbphrase['no']) . iif(vB_Template_Runtime::fetchStyleVar('textdirection') == 'rtl', "&rlm;") . "</label>" .
        iif($value == 2 AND $name == 'customtitle', "
            <label for=\"rb_2_{$name}_$uniqueid\"><input type=\"radio\" name=\"$name\" id=\"rb_2_{$name}_$uniqueid\" value=\"2\" tabindex=\"1\"$onclick" . iif($vbulletin->debug, " title=\"name=&quot;$name&quot; value=&quot;2&quot;\"") . " checked=\"checked\" />$vbphrase[yes_but_not_parsing_html]</label>"
        ) . "\n\t</div>";
}

function print_color_cell($id, $value)
{
    global $vbulletin;
    $name = "color[$id]";
    $numcolors = $id;
    $size = 20;
    $background = $value ? $value : 'none';
        return(
        "<div id=\"ctrl_$name\" style=\"width:200px;\">
            <input style=\"float:" . vB_Template_Runtime::fetchStyleVar('left') . "; margin-" . vB_Template_Runtime::fetchStyleVar('right') . ": 4px\" type=\"text\" class=\"" . iif($inputclass, $inputclass, 'bginput') . "\" name=\"$name\" id=\"color_$numcolors\" value=\"" . iif($htmlise, htmlspecialchars_uni($value), $value) . "\" size=\"$size\"" . iif($maxlength, " maxlength=\"$maxlength\"") . " dir=\"$direction\" tabindex=\"1\"" . iif($vbulletin->debug, " title=\"name=&quot;$name&quot;\"") . " onchange=\"preview_color($numcolors)\" />
            <div style=\"float:" . vB_Template_Runtime::fetchStyleVar('left') . ";background: $background;border-style: dashed;background-position:initial initial;background-repeat:initial initial;\" id=\"preview_$numcolors\" class=\"colorpreview\" onclick=\"open_color_picker($numcolors, event)\"></div>
        </div>"
    );
}
?>