/**
 * Get the path to the resource as (breadcrumbs)
 * 
 * @param array $params
 * @param Smarty $smarty
 * 
 * @return string 
 */
function smarty_function_breadcrumbs($params, $smarty)
{
    $defaultParams = array('trail' => array(), 'separator' => ' > ', 'truncate' => 40);
    // initialize the parameters
    foreach ($defaultParams as $k => $v) {
        if (!isset($params[$k])) {
            $params[$k] = $v;
        }
    }
    // load the truncate modifier
    if ($params['truncate'] > 0) {
        require_once $smarty->_get_plugin_filepath('modifier', 'truncate');
    }
    $links = array();
    $numSteps = count($params['trail']);
    for ($i = 0; $i < $numSteps; $i++) {
        $step = $params['trail'][$i];
        // truncate the title if required
        if ($params['truncate'] > 0) {
            $step['title'] = smarty_modifier_truncate($step['title'], $params['truncate']);
        }
        // build the link if it's set and isn't the last step
        if (strlen($step['link']) > 0 && $i < $numSteps - 1) {
            $links[] = sprintf('<a href="%s" title="%s">%s</a>', htmlSpecialChars($step['link']), htmlSpecialChars($step['title']), htmlSpecialChars($step['title']));
        } else {
            // either the link isn't set, or it's the last step
            $links[] = htmlSpecialChars($step['title']);
        }
    }
    // join the links using the specified separator
    return join($params['separator'], $links);
}
/**
 * Wrap form field into a DIV
 * 
 * Properties:
 * 
 * - field - field name
 * - errors - errors container (ValidationErrors instance)
 * - show_errors - show errors list inside of field wrapper
 *
 * @param array $params
 * @param string $content
 * @param Smarty $smarty
 * @param boolean $repeat
 * @return null
 */
function smarty_block_wrap($params, $content, &$smarty, &$repeat)
{
    $field = array_var($params, 'field');
    if (empty($field)) {
        return new InvalidParamError('field', $field, "'field' property is required for 'wrap_field' helper", true);
    }
    // if
    $classes = array();
    if (isset($params['class'])) {
        $classes = explode(' ', $params['class']);
        unset($params['class']);
    }
    // if
    if (!in_array('ctrlHolder', $classes)) {
        $classes[] = 'ctrlHolder';
    }
    // if
    $error_messages = null;
    if (isset($params['errors'])) {
        $errors = $params['errors'];
    } else {
        $errors = $smarty->get_template_vars('errors');
    }
    // if
    if (instance_of($errors, 'ValidationErrors')) {
        if ($errors->hasError($field)) {
            $classes[] = 'error';
            $error_messages = $errors->getFieldErrors($field);
        }
        // if
    }
    // if
    $show_errors = array_var($params, 'show_errors', true);
    $listed_errors = '';
    if (is_foreachable($error_messages) && $show_errors) {
        require_once $smarty->_get_plugin_filepath('function', 'field_errors');
        $listed_errors = smarty_function_field_errors(array('field' => $field, 'errors' => $errors), $smarty);
    }
    // if
    $aid = array_var($params, 'aid');
    if ($aid) {
        $aid = '<p class="aid">' . clean(lang($aid)) . '</p>';
    }
    // if
    // Unset helper properties, we need this for attributes
    unset($params['field']);
    unset($params['errors']);
    unset($params['show_errors']);
    unset($params['aid']);
    $params['class'] = implode(' ', $classes);
    return open_html_tag('div', $params) . "\n{$listed_errors}\n" . $content . $aid . "\n</div>";
}
/**
 * Get an image file
 *
 * @param array $params
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_imagefilename($params, $smarty)
{
    if (!isset($params['id'])) {
        $params['id'] = 0;
    }
    if (!isset($params['w'])) {
        $params['w'] = 0;
    }
    if (!isset($params['w'])) {
        $params['h'] = 0;
    }
    require_once $smarty->_get_plugin_filepath('function', 'geturl');
    $hash = Default_Model_DbTable_BlogPostImage::GetImageHash($params['id'], $params['w'], $params['h']);
    $options = array('controller' => 'utility', 'action' => 'image');
    return sprintf('%s?username=%s&id=%d&w=%d&h=%d&hash=%s', smarty_function_geturl($options, $smarty), $params['username'], $params['id'], $params['w'], $params['h'], $hash);
}
/**
 * Smarty {scaffold} function plugin
 *
 * Type:     function<br>
 * Name:     scaffold<br>
 * Purpose:  scaffold
 *
 * @param         $params
 * @param \Smarty $smarty
 * @return bool
 */
function smarty_function_scaffold($params, &$smarty)
{
    if (isset($params['model'])) {
        global $db;
        require_once $smarty->_get_plugin_filepath('function', 'control');
        $table = $db->getDataDefinition($params['model']);
        foreach ($table as $key => $col) {
            if ($key != 'created_at' && $key != 'edited_at' && $key != 'poster' && $key != 'editor' && $key != 'location_data') {
                $ctl = array();
                //Get the default value
                if (isset($params['item'])) {
                    $ctl['value'] = isset($params['item']->{$key}) ? $params['item']->{$key} : "";
                }
                //Get the base control
                if ($key == 'id') {
                    $ctl['type'] = 'hidden';
                } else {
                    $ctl['type'] = expTemplate::guessControlType($col, $default_value, $key);
                }
                //format the values if needed
                if (isset($col[FORM_FIELD_FILTER])) {
                    switch ($col[FORM_FIELD_FILTER]) {
                        case MONEY:
                        case DECIMAL_MONEY:
                            $ctl['value'] = expCore::getCurrencySymbol('USD') . number_format($ctl['value'], 2, '.', ',');
                            $ctl['filter'] = 'money';
                            break;
                    }
                }
                //write out the control itself...and then we're done.
                if (isset($col[FORM_FIELD_ONCLICK])) {
                    $ctl['onclick'] = $col[FORM_FIELD_ONCLICK];
                }
                $ctl['label'] = isset($col[FORM_FIELD_LABEL]) ? $col[FORM_FIELD_LABEL] : $key;
                $ctl['name'] = isset($col[FORM_FIELD_NAME]) ? $col[FORM_FIELD_NAME] : $key;
                echo smarty_function_control($ctl, $smarty);
                //echo $control->controlToHTML($control_label, $control_name);
            }
        }
    }
    $submit = new buttongroupcontrol(gt('Submit'), gt('Reset'), gt('Cancel'));
    echo $submit->controlToHTML('submit');
}
/**
 * Zikula_View function to display a drop down list of languages
 *
 * Available parameters:
 *   - assign:   If set, the results are assigned to the corresponding variable instead of printed out
 *   - name:     Name for the control
 *   - id:       ID for the control
 *   - selected: Selected value
 *   - installed: if set only show languages existing in languages folder
 *   - all:      show dummy entry '_ALL' on top of the list with empty value
 *
 * Example
 *   {html_select_locales name=locale selected=en}
 *
 * @param array  $params All attributes passed to this function from the template.
 * @param Smarty $view   Reference to the Zikula_View object.
 *
 * @return string The value of the last status message posted, or void if no status message exists.
 */
function smarty_function_html_select_locales($params, Smarty $view)
{
    if (!isset($params['name']) || empty($params['name'])) {
        $view->trigger_error(__f('Error! in %1$s: the %2$s parameter must be specified.', array('html_select_locales', 'name')));
        return false;
    }
    require_once $view->_get_plugin_filepath('function', 'html_options');
    $values = $output = array();
    if (isset($params['all']) && $params['all']) {
        $values[] = '';
        $output[] = DataUtil::formatForDisplay(__('All'));
    }
    $installed = ZLanguage::getInstalledLanguageNames();
    $output = array_merge($output, DataUtil::formatForDisplay(array_values($installed)));
    $values = array_merge($values, DataUtil::formatForDisplay(array_keys($installed)));
    $html_result = smarty_function_html_options(array('output' => $output, 'values' => $values, 'selected' => isset($params['selected']) ? $params['selected'] : null, 'id' => isset($params['id']) ? $params['id'] : null, 'name' => $params['name']), $view);
    if (isset($params['assign']) && !empty($params['assign'])) {
        $view->assign($params['assign'], $html_result);
    } else {
        return $html_result;
    }
}
/**
 * Smarty {prod_images} function plugin
 *
 * Type:     function<br>
 * Name:     prod_images<br>
 * Purpose:  display product images
 *
 * @param         $params
 * @param \Smarty $smarty
 * @return bool
 */
function smarty_function_prod_images($params, &$smarty)
{
    //load up the img plugin
    require_once $smarty->_get_plugin_filepath('function', 'img');
    $rec = $params['record'];
    if ($rec->main_image_functionality == 'iws') {
        $images = $rec->expFile['imagesforswatches'];
    } else {
        $images = $rec->expFile['mainimage'];
    }
    //ref for additional images so we can play with the array
    $additionalImages = !empty($rec->expFile['images']) ? $rec->expFile['images'] : array();
    $mainImages = !empty($additionalImages) ? array_merge($images, $additionalImages) : $images;
    $mainthmb = !empty($rec->expFile['mainthumbnail'][0]) ? $rec->expFile['mainthumbnail'][0] : $mainImages[0];
    $addImgs = array_merge(array($mainthmb), $additionalImages);
    //pulling in store configs. This is a placeholder for now, so we'll manually set them til we get that worked in.
    $config = $smarty->getTemplateVars('config');
    // $config = array(
    //     "listing-width"=>148,
    //     "listing-height"=>148,
    //     "disp-width"=>200,
    //     "disp-height"=>250,
    //     "thmb-box"=>40,
    //     "swatch-box"=>30,
    //     "swatch-pop"=>100
    //     );
    switch ($params['display']) {
        case 'single':
            $html = '<a class="prod-img" href="' . makelink(array("controller" => "store", "action" => "showByTitle", "title" => $rec->title)) . '">';
            $width = !empty($params['width']) ? $params['width'] : 100;
            $imgparams = array("constraint" => 1, "file_id" => $images[0]->id, "w" => $config["listingwidth"], "h" => $config["listingheight"], "return" => 1, "class" => "ecom-image");
            if (!$images[0]->id) {
                unset($imgparams['file_id']);
                $imgparams['src'] = 'framework/modules/ecommerce/assets/images/no-image.jpg';
                $imgparams['alt'] = gt('No image found for') . ' ' . $rec->title;
            }
            $img = smarty_function_img($imgparams, &$smarty);
            $html .= $img;
            $html .= '</a>';
            break;
        case 'main':
            // if we have only 1 image to display, left do a little math to figure out how tall to make our display box
            if (count($addImgs) <= 1) {
                $config['displayheight'] = ceil($mainImages[0]->image_height * $config['displaywidth'] / $mainImages[0]->image_width);
            }
            if (count($addImgs) > 1) {
                $adi .= '<ul class="thumbnails">';
                for ($i = 0; $i < count($addImgs); $i++) {
                    $thumbparams = array("h" => $config['addthmbw'], "w" => $config['addthmbh'], "zc" => 1, "file_id" => $addImgs[$i]->id, "return" => 1, "class" => "thumnail");
                    $thmb .= '<li>' . smarty_function_img($thumbparams, &$smarty) . '</li>';
                }
                $adi .= $thmb;
                $adi .= '</ul>';
            }
            // shrink shrink the display window to fit the selected image if no height is set
            if ($config['displayheight'] == 0) {
                $config['displayheight'] = $config['displaywidth'] * $mainImages[0]->image_height / $mainImages[0]->image_width;
            }
            $html = '<div class="ecom-images loading-images" style="width:' . $config['displaywidth'] . 'px;">';
            // if configured, the additional thumb images will display at the bottom
            $html .= $config['thumbsattop'] == 1 ? $adi : '';
            $html .= '<ul class="enlarged" style="height:' . $config['displayheight'] . 'px;width:' . $config['displaywidth'] . 'px;">';
            for ($i = 0; $i < count($mainImages); $i++) {
                $imgparams = array("w" => $config['displaywidth'], "file_id" => $mainImages[$i]->id, "return" => 1, "class" => "large-img");
                $img .= '<li>' . smarty_function_img($imgparams, &$smarty) . '</li>';
            }
            $html .= $img;
            $html .= '</ul>';
            // if configured, the additional thumb images will display at the bottom
            $html .= $config['thumbsattop'] != 1 ? $adi : '';
            $html .= '</div>';
            // javascripting
            $js = "\n                YUI(EXPONENT.YUI3_CONFIG).use('node','anim', function(Y) {\n                    // set up the images with correct z-indexes to put the first image on top\n                    var imgs = Y.all('.ecom-images img.large-img');\n                    var thumbs = Y.all('.thumbnails img');\n                    var swatches = Y.all('.swatches .swatch');\n\n                    //remove loading\n                    Y.one('.loading-images').removeClass('loading-images');\n\n                    var resetZ = function(n,y){\n                        n.setStyles({'zIndex':0,'display':'none'});\n                        n.set('id','exp-ecom-msi-'+y);\n                    }\n\n                    imgs.each(resetZ);\n                    imgs.item(0).setStyles({'zIndex':'1','display':'block'});\n                    \n                    swatches.each(function(n,y){\n                        n.set('id','exp-ecom-ms-'+y)\n                    });\n                    \n                    swatches.on('click',function(e){\n                        imgs.each(resetZ);\n                        var curImg = imgs.item(swatches.indexOf(e.target));\n                        var imgWin = curImg.ancestor('ul.enlarged');\n                        imgWin.setStyle('height',curImg.get('height')+'px');\n                        //animImgWin(imgWin,curImg.get('height'));\n                        curImg.setStyles({'zIndex':'1','display':'block'});\n                    });\n                \n                    thumbs.on('click',function(e){\n                        imgs.each(resetZ);\n                        \n                        if (swatches.size()!=0) {\n                            var processedIndex = thumbs.indexOf(e.target)==0 ? 0 : swatches.size()+thumbs.indexOf(e.target)-1;\n                        } else {\n                            var processedIndex = thumbs.indexOf(e.target);\n                        }\n                        var curImg = imgs.item(processedIndex);   \n                        curImg.ancestor('ul.enlarged').setStyle('height',curImg.get('height')+'px');                \n                        curImg.setStyles({'zIndex':'1','display':'block'});\n                    });\n                    \n                    // animation...  too much for now, but we'll leave the code\n                    var animImgWin = function (node,h) {\n                        var hAnim = new Y.Anim({\n                                node: node,\n                                to: {height: h},\n                                easing:Y.Easing.easeOut,\n                                duration:0.5\n                        });\n                        hAnim.run();\n                    }\n                \n                });\n            ";
            expJavascript::pushToFoot(array("unique" => 'imgswatches', "yui2mods" => null, "yui3mods" => null, "content" => $js, "src" => ""));
            break;
        case 'swatches':
            $html = '<ul class="swatches">';
            $swatches = $rec->expFile['swatchimages'];
            for ($i = 0; $i < count($swatches); $i++) {
                $small = array("h" => $config['swatchsmh'], "w" => $config['swatchsmw'], "zc" => 1, "file_id" => $swatches[$i]->id, "return" => 1, "class" => 'swatch');
                $med = array("h" => $config['swatchpoph'], "w" => $config['swatchpopw'], "zc" => 1, "file_id" => $swatches[$i]->id, "return" => 1);
                $swtch .= '<li>' . smarty_function_img($small, &$smarty);
                $swtch .= '<div>' . smarty_function_img($med, &$smarty) . '<strong>' . $swatches[$i]->title . '</strong></div>';
                $swtch .= '</li>';
            }
            $html .= $swtch;
            $html .= '</ul>';
            break;
    }
    echo $html;
}