<?php

/**
 * Class PA
 *
 */
class PA
{

    public static function head($css_array, $data = '')
    {
        $head =
    '<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta charset="UTF-8">';
        if (!PA::isAdminArea()) {
            $head .= PA::getSEO($data);
        }
        $head .=
            '<title>'.PA::getTitle($data).'</title>';
        if (PA::isAdminArea()) {
            $head .= Admin::adminGetCSS();
        }
        $head .= PA::loadCss($css_array).
        PA::loadFavicon().
        '
    <script>
        document.createElement("header");
        document.createElement("nav");
        document.createElement("section");
        document.createElement("footer");
    </script>
';
        return $head;
    }

    public static function getSEO($data = '', $seodata = '')
    {
        $keywords       = '';
        $sitename       = Helper::cleanForOutput(Config::getFromDB('MarketName'));
        $url            = Helper::getCurrentURL();
        $author         = $sitename;
        $title          = PA::getTitle($data);
        $date           = '';
        $placename      = '';

        $platformLogo   = Config::getFromDB('MarketLogo');
        if ($platformLogo != '') {
            $img = explode(':', $platformLogo);
            $image = PA::getImageURL().$img[0].'logo_big'.$img[1];
        } else {
            $image = '';
        }

        if (PA::isPage()) {
            $text = $data['page']->body;
            $description = strip_tags($text);
        } elseif (PA::isProfilePage()) {
            $userlogo   = $data["profile"]->company_logo_path;
            if ($userlogo != '') {
                $img = explode(':', $userlogo);
                $image = PA::getImageURL().$img[0].'logo_big'.$img[1];
            }
            $description = Helper::cleanForOutput($data["profile"]->company_short_info);
        } elseif (PA::isOfferPage()) {
            if ($data["offer"]->image) {
                $image = PA::getPictureURL($data["offer"]->image,'big','offer');
            }
            $description = Helper::cleanForOutput($data["offer"]->detail);
            $category1 = Text::get('CATEGORY1');
            $category2 = Text::get('CATEGORY2');

            if ($data["offer"]->category1) { $keywords .= $category1[$data["offer"]->category1].', '; }
            if ($data["offer"]->category2) { $keywords .= $category2[$data["offer"]->category2][0].', '; }
            $keywords .= $data["offer"]->tags;
        } else {
            $description = Helper::cleanForOutput(Config::getFromDB('MarketDetailShort'));
        }

        if (strlen($description) > 250) {
            $description = mb_substr($description, 0, 245).'[...]';
        }

        $description_og = $description;
        $keywords_og    = $keywords;

        $return_seo = '
    <meta name="keywords" content="'.$keywords.'" />
    <meta name="description" content="'.$description.'">
    <meta name="author" content="'.$author.'" />
    <meta name="date" content="'.$date.'" />
    <meta name="generator" content="peeragora" />
    <meta name="geo.placename" content="'.$placename.'" />
    <meta property="og:site_name" content="'.$sitename.'" />
    <meta property="og:url" content="'.$url.'" />
    <meta property="og:title" content="'.$title.'" />
    <meta property="og:description" content="'.$description_og.'" />
    <meta property="og:article:tag" content="'.$keywords_og.'" />
    <meta property="og:image" content="'.$image.'" />
        ';
    return $return_seo;
    }

    public static function getTitle($data = '')
    {
        if (PA::isPage()) {
            $title = Helper::cleanForOutput(Config::getFromDB('MarketName'))
            . ' - '.Helper::cleanForOutput($data['page']->title);
        } elseif (PA::isProfilePage()) {
            $title = Helper::cleanForOutput(Config::getFromDB('MarketName'))
            . ': '.Helper::cleanForOutput($data['profile']->company_name);
            if ($data['profile']->company_claim != '') {
                $title .= ' - '.Helper::cleanForOutput($data['profile']->company_claim);
            }
        } elseif(PA::isOfferPage()) {
            $title = Helper::cleanForOutput(Config::getFromDB('MarketName'))
            . ': '.Helper::cleanForOutput($data['profile']->company_name);
            if ($data['offer']->title != '') {
                $title .= ' - '.Helper::cleanForOutput($data['offer']->title);
            }
        } else {
            $title = Helper::cleanForOutput(Config::getFromDB('MarketName'))
            . ' - ' .Helper::cleanForOutput(Config::getFromDB('MarketClaim'));
        }
        return $title;
    }

    public static function getVersion()
    {
        return Config::getFromDB('MarketVersion');
    }

    public static function loadCss($css_array)
    {
        $include_css = '';
        foreach ($css_array as $style_name => $target) {
            $css_path           = Theme::get('URL').'css/'.$style_name.'.css';
            $test_path          = Theme::get('PATH').'css/'.$style_name.'.css';
            if (!file_exists($test_path)) {
                $baseurl        = Theme::get('BASEURL');
                $parent_name    = Theme::getConfig('PARENT');
                $css_path       = $baseurl.$parent_name.'/css/'.$style_name.'.css';
            }

            if (!isset($target)) { $target = 'screen'; }
            $include_css .= '
    <link href="'.$css_path.'" rel="stylesheet" type="text/css" media="'.$target.'">';
        }
        if (PA::isAdminArea()) {
            $include_css .= '
    <link href="'.PA::getBaseURL().'libs/dropzone.css" rel="stylesheet" type="text/css" media="screen">';
            $include_css .= '
    <link href="'.PA::getBaseURL().'libs/cleditor/jquery.cleditor.css" rel="stylesheet" type="text/css" media="screen">';
        }

        $include_css .= PA::loadPluginCss();

        return $include_css;
    }

    public static function loadPluginCss()
    {
        $path = Plugin::get('URL',"imgedit").'css/filter.css';
        $path2 = Plugin::get('URL',"imgedit").'css/cropper.css';
        $path3 = Plugin::get('URL',"imgedit").'css/bricklayer.css';
        $return_css = '
    <link href="'.$path.'" rel="stylesheet" type="text/css" media="screen">
    <link href="'.$path2.'" rel="stylesheet" type="text/css" media="screen">
    <link href="'.$path3.'" rel="stylesheet" type="text/css" media="screen">';
        return $return_css;
    }

    public static function loadFavicon()
    {
        $favicon_path = Config::get('PATH_THEMES')
                    .Config::getFromDB('MarketUsedTheme').'/img/favicon.ico';
        if (file_exists($favicon_path)) {
            $favicon_url = Theme::get('URL').'img/favicon.ico';
            return '
    <link href="'.$favicon_url.'" rel="icon">';
        }
    }

    public static function loadJS()
    {
        $dropzone_path = PA::getBaseURL()
                    .'libs/dropzone.min.js';
        $jquery_path = PA::getBaseURL()
                    .'libs/jquery.min.js';
        $cleditor_path = PA::getBaseURL()
                    .'libs/cleditor/jquery.cleditor.js';
        $cleditor_table_path = PA::getBaseURL()
                    .'libs/cleditor/jquery.cleditor.table.min.js';
        $format_xml_path = PA::getBaseURL()
                    .'libs/formatXML.js';

        include(Config::get('PATH_VIEW') . 'admin/scripts_js.php');
        $scripts = $admin_js_scripts;

        if (PA::isAdminArea()) {
            $script_return = '
                <script src="'.$dropzone_path.'"></script>
                <script src="'.$jquery_path.'"></script>
                <script src="'.$cleditor_path.'"></script>
                <script src="'.$cleditor_table_path.'"></script>
                <script src="'.$format_xml_path.'"></script>
                <script type="text/javascript">'.$scripts.'</script>
                ';
        } else {
            $script_return = '
                <script src="'.$jquery_path.'"></script>
                <script type="text/javascript">
                    var timeout = 5000;
                    (function poll() {
                       setTimeout(function() {
                          $.ajax({ url: "'.$sync_url.'", success: function(data) {
                            if (data.backoff >= 20 && timeout >= 60000)
                            {
                              timeout = timeout*2;
                              if (timeout > 600000)
                              {
                                timeout = 600000;
                              }
                            } else {
                              timeout = data.backoff * 1000;
                            }
                            poll();
                          }, dataType: "json"}).fail(function() {
                            timeout = 180000;
                          });
                      }, timeout);
                    })();
                </script>
                <script type="text/javascript">
                    var elems = document.getElementsByClassName("delete_button");
                    var confirmIt = function (e) {
                        if (!confirm("'.Text::get('CONFIRM_DELETE').'")) e.preventDefault();
                    };
                    for (var i = 0, l = elems.length; i < l; i++) {
                        elems[i].addEventListener("click", confirmIt, false);
                    }
                </script>
                ';
        }

        if (View::getTheFileName() == 'settings' ||
            View::getTheFileName() == 'editProfile' ||
            View::getTheFileName() == 'editOffer' ||
            View::getTheFileName() == 'editPage') {
            $script_return .= '
                <script type="text/javascript">
                    $(".form_element").on("change keyup paste", function() {
                        window.onbeforeunload = function() {
                            return "'.Text::get('GO_REALLY').'";
                        };
                    })
                    $(".form_submit").click(function() {
                        window.onbeforeunload = null;
                    });
                </script>
                ';
        }
        $script_return .= Plugin::loadPluginJS();

        return $script_return;
    }

    public static function showMenu($menuname, $menuhead = '')
    {
        //// SHAREMENU
        if ($menuname == 'sharemenu') {
            $headon = '';

            $emaillink      = 'mailto:?subject='.Helper::cleanForOutput(Config::getFromDB('MarketName')).'-'.Helper::cleanForOutput(Config::getFromDB('MarketClaim')).'&body='.Helper::getCurrentURL();
            $facebooklink   = 'https://www.facebook.com/sharer/sharer.php?u='.Helper::getCurrentURL();
            $twitterlink    = 'https://twitter.com/home?status='.Helper::getCurrentURL().' #'.Config::getFromDB('MarketName');
            $googlelink     = 'https://plus.google.com/share?url='.Helper::getCurrentURL();
            if ($menuhead) {
                $headon = 1;

                if (preg_match('/(\.jpg|\.png|\.bmp|\.gif)$/', $menuhead)) {
                    $menuhead = '<img src="'.$menuhead.'" class="menuhead_img">';
                }
            }
            echo '
            <ul class="menu">
                <li>
                    <span class="menuhead">'.$menuhead.'</span>
            ';
            echo '
            <ul>';
            echo '<li><a href="'.$emaillink.'" target="_blank">'.Text::get('MENU_SHARE_MAIL').'</a></li>';
            echo '<li><a href="'.$facebooklink.'" target="_blank">'.Text::get('MENU_SHARE_FACEBOOK').'</a></li>';
            echo '<li><a href="'.$twitterlink.'" target="_blank">'.Text::get('MENU_SHARE_TWITTER').'</a></li>';
            echo '<li><a href="'.$googlelink.'" target="_blank">'.Text::get('MENU_SHARE_GOOGLE').'</a></li>';

            echo '
                </ul>
            ';
            echo '</li></ul>';
        }
        //// MAINMENU
        elseif ($menuname == 'mainmenu') {
            $headon = '';
            if ($menuhead) {
                $headon = 1;

                if (preg_match('/(\.jpg|\.png|\.bmp|\.gif)$/', $menuhead)) {
                    $menuhead = '<img src="'.$menuhead.'" class="menuhead_img">';
                }
            }
            echo '
            <ul class="menu">
                <li>
                    <a href="'.PA::getHomeURL().'">
                        <span class="menuhead">'.$menuhead.'</span>
                    </a>
            ';
            echo '
                <ul>';
            echo '<li><a href="'.PA::getLink('offers').'">'.Text::get('MENU_ALL_OFFERS').'</a></li>';
            echo '<li><a href="'.PA::getLink('requests').'">'.Text::get('MENU_ALL_REQUESTS').'</a></li>';
            echo '<li><a href="'.PA::getLink('all_users').'">'.Text::get('MENU_ALL_USERS').'</a></li>';
            echo '<li><a href="'.PA::getLink('all_users_other').'">'.Text::get('MENU_ALL_USERS_OTHER').'</a></li>';
            Plugin::showPluginLinks($menuname);

            echo '
                </ul>
            ';
            echo '</li></ul>';
        }
        //// PAGESMENU
        elseif ($menuname == 'pagesmenu') {
            $headon = '';
            if ($menuhead) {
                $headon = 1;

                if (preg_match('/(\.jpg|\.png|\.bmp|\.gif)$/', $menuhead)) {
                    $menuhead = '<img src="'.$menuhead.'" class="menuhead_img">';
                }
            }
            echo '
            <ul class="menu">
                <li><span class="menuhead">'.$menuhead.'</span>
            ';
            echo '
                <ul>';
                $pages = PageModel::getPages();
                foreach($pages as $page) {
                    echo '<li><a href="'.PA::getURL().'pages/view/'.$page->slug.'">'.$page->title.'</a></li>';
                }
                Plugin::showPluginLinks($menuname);
            echo '
                </ul>
            ';
            echo '</li></ul>';
        }

        //// USERMENU
        elseif ($menuname == 'usermenu') {
            $headon = '';
            if ($menuhead) {
                $headon = 1;
                if (preg_match('/(\.jpg|\.png|\.bmp|\.gif)$/', $menuhead)) {
                    $menuhead = '<img src="'.$menuhead.'" class="menuhead_img">';
                }
            }
            echo '
            <ul class="menu">
                <li><span class="menuhead">'.$menuhead.'</span>
            ';

            if (Session::userIsLoggedIn()) {
                echo '
                    <ul>
                        <li><a href="'.PA::getLink('profile').'">'.Text::get('MENU_OVERVIEW').'</a></li>
                        <li><a href="'.PA::getLink('newOffer').'">'.Text::get('MENU_NEW_OFFER').'</a></li>
                        <li><a href="'.PA::getLink('viewOwnProfile').'">'.Text::get('MENU_MY_PROFILE').'</a></li>
                        <li><a href="'.PA::getLink('editOwnProfile').'">'.Text::get('MENU_EDIT_PROFILE').'</a></li>';
                        Plugin::showPluginLinks($menuname);
                echo '
                        <li><a href="'.PA::getLink('logout').'">'.Text::get('MENU_LOGOUT').'</a></li>
                    </ul>';
            } else {
                echo '
                    <ul>';
                    if (PA::getRegisterStatus() > 0) {
                        echo '
                        <li><a href="'.PA::getLink('register').'">'.Text::get('MENU_JOIN').'</a></li>';
                    }
                        echo '
                        <li><a href="'.PA::getLink('login').'">'.Text::get('MENU_LOGIN').'</a></li>
                    </ul>';
            }
                echo '
              </li>
            </ul>
            ';
        }

        //// ADMINMENU
        elseif ($menuname == 'adminmenu') {
            $headon = '';
            if (PA::isSuperAdmin()) {
                if ($menuhead) {
                    $headon = 1;
                    if (preg_match('/(\.jpg|\.png|\.bmp|\.gif)$/', $menuhead)) {
                        $menuhead = '<img src="'.$menuhead.'" class="menuhead_img">';
                    }
                    echo '
                    <ul class="menu">
                        <li><span class="menuhead">'.$menuhead.'</span>
                    ';
                }

                echo '
                    <ul>
                        <li><a href="'.PA::adminGetLink('index').'">'.Text::get('MENU_ADMIN_OVERVIEW').'</a></li>
                        <li><a href="'.PA::adminGetLink('settings').'">'.Text::get('MENU_ADMIN_SETTINGS').'</a></li>
                        <li><a href="'.PA::adminGetLink('connections').'">'.Text::get('MENU_ADMIN_CONNECTIONS').'</a></li>
                        <li><a href="'.PA::adminGetLink('users').'">'.Text::get('MENU_ADMIN_USERS').'</a></li>
                        <li><a href="'.PA::adminGetLink('offers').'">'.Text::get('MENU_ADMIN_OFFERS').'</a></li>
                        <li><a href="'.PA::adminGetLink('pages').'">'.Text::get('MENU_ADMIN_PAGES').'</a></li>
                        <li><a href="'.PA::adminGetLink('plugins').'">'.Text::get('MENU_ADMIN_PLUGINS').'</a></li>';
                        Plugin::showPluginLinks($menuname);
                echo '
                    </ul>';
            }

            if ($headon == 1) {
                echo '
              </li>
            </ul>
            ';
            }
        }
    }

    public static function showHeadline($type, $searchtext, $img = '', $class = '')
    {
        $return = '
            <'.$type.' class="headline '.$class.'">'.$searchtext;
        if ($img != '') {
            $return .= '<div class="headline_img"><img src="'.PA::getThemeURL().'img/'.$img.'"></div>';
        }
        $return .= '</'.$type.'>';
        echo $return;
    }

    public static function showMarketName($headline = 'h1', $link = false)
    {
        $marketName = Helper::cleanForOutput(Config::getFromDB('MarketName'));
        $marketClaim = Helper::cleanForOutput(Config::getFromDB('MarketClaim'));
        if ($link === true) {
            echo '<'.$headline.' class="market_name">
                    <a href="'.PA::getHomeURL().'" title="'
                        .$marketName.' - '.$marketClaim.'">'
                        .$marketName.'
                    </a>
                </'.$headline.'>';
        } else {
            echo '<'.$headline.' class="market_name">
                        '.$marketName.'
                </'.$headline.'>';
        }
    }

    public static function showUserName($details, $headline = 'h1', $link = false)
    {
        $marketName = Helper::cleanForOutput($details->company_name);
        $marketClaim = Helper::cleanForOutput($details->company_claim);
        if ($link === true) {
            echo '<'.$headline.' class="market_name">
                    <a href="'.PA::getHomeURL().'" title="'
                        .$marketName.' - '.$marketClaim.'">'
                        .$marketName.'
                    </a>
                </'.$headline.'>';
        } else {
            echo '<'.$headline.' class="market_name">
                        '.$marketName.'
                </'.$headline.'>';
        }
    }

    public static function showMarketClaim($headline = 'h2')
    {
        $marketClaim = Helper::cleanForOutput(Config::getFromDB('MarketClaim'));
        echo '<'.$headline.' class="market_slogan">'
                .$marketClaim.'</'.$headline.'>';
    }

    public static function showUserClaim($details, $headline = 'h2')
    {
        $marketClaim = Helper::cleanForOutput($details->company_claim);
        echo '<'.$headline.' class="market_slogan">'
                .$marketClaim.'</'.$headline.'>';
    }

    public static function showMarketLogo()
    {
        $marketName = Helper::cleanForOutput(Config::getFromDB('MarketName'));
        $marketClaim = Helper::cleanForOutput(Config::getFromDB('MarketClaim'));
        $marketLogo = Config::getFromDB('MarketLogo');
        if ($marketLogo != '') {
            $img = explode(':', $marketLogo);
            echo '
            <div id="header_logo" class="transition">
                <a href="'.PA::getHomeURL().'" title="'
                    .$marketName.' - '.$marketClaim.'">
                    <img src="'.PA::getImageURL()
                        .$img[0].'logo_medium'.$img[1].'" alt="'.$marketName.'">
                </a>
            </div>';
        }
    }

    public static function showUserLogo($details)
    {
        if (!is_null($details->company_logo_path)) {
            $marketName = Helper::cleanForOutput($details->company_name);
            $marketClaim = Helper::cleanForOutput($details->company_claim);
            $profile_id = $details->id;
            $img = explode(':', $details->company_logo_path);
            echo '
            <div id="header_logo" class="transition">
                <a href="'.PA::getLink('user',$details->slug).'" title="'
                    .$marketName.' - '.$marketClaim.'">
                    <img src="'.PA::getImageURL()
                        .$img[0].'logo_medium'.$img[1].'" alt="'.$marketName.'">
                </a>
            </div>';
        }
    }

    public static function showElement($element)
    {
        if (!$element) {
            return false;
        } else {
            Theme::loadfile($element.'.php');
        }
    }

    public static function showSidebar()
    {
        Theme::loadfile('sidebar.php');
    }

    public static function showHeader()
    {
        // DEPRECATED
        //require Theme::get('path') . 'header.php';
    }

    public static function showFooter()
    {
        Theme::loadfile('footer.php');
    }

    public static function showImageUploader($type,$imageSize,$id,$path,$text)
    {
        if (!is_null($path) && $path !='') {
            $img = explode(':', $path);
            $bgImage = ' style="background-image: url('
                .PA::getImageURL()
                .$img[0]
                .$imageSize
                .$img[1].')"';
        } else {
            $bgImage = '';
        }
        echo '
            <div class="edit_sidebar_box '.$type.'"'.$bgImage.'>
                <label class="edit_sidebar_label"><span>'.$text.'</span></label>';
                if ($path) {
                    echo '
                    <a href="'.PA::getlink('delete_image',$id).'/'.$type.'">
                        <div class="edit_sidebar_delete_button"></div>
                    </a>';
                }
                echo '
                <form action="'.PA::getURL().'upload/'.$type.'/'.$id.'" method="post" class="dropzone">
                    <div class="dz-message"><span>'.Text::get('IMAGE_UPLOAD_TEXT').'</span></div>
                </form>
            </div>';
    }

    public static function showSearchbar($searchtext = '', $searchterm = '', $custom = '')
    {
        $old_searchterm = ucwords(str_replace("+", " ", $searchterm));
        echo '
        <div id="search">
            <form method="post" action="'.Config::getURL().'search" accept-charset="UTF-8" id="search_form">
                <input type="text" name="search" placeholder="'
                    .Text::get('SEARCHBAR_INPUT_PLACEHOLDER').'" value="'
                    .$old_searchterm.'" id="search_input" class="form_element">';

                echo '
                <div id="search_zip_input_box">
                    <input type="text" name="search_zip" placeholder="'
                        .Text::get('SEARCHBAR_PLACEHOLDER_DETAILS_ZIP').'" value="'
                        .Session::get('search_plz').'" id="search_zip_input" class="form_element">
                </div>
                ';

                echo '
                <input type="submit" value="'.$searchtext.'" id="search_submit" class="form_submit">';
                if ($custom == true) {
                    $searchOffers   = (in_array(Session::get('search_offers'), array('y','')) ? ' checked':'');
                    $searchRequests = (in_array(Session::get('search_requests'), array('y','')) ? ' checked':'');
                    $searchInternal = (in_array(Session::get('search_internal'), array('y','')) ? ' checked':'');
                    $searchExternal = (in_array(Session::get('search_external'), array('y','')) ? ' checked':'');
                    echo '
                    <div id="search_details" class="transition">
                        <a href="#">
                            <div id="search_details_close"></div>
                        </a>

                        <div id="search_details_button" class="transition">
                            <a href="#search">
                                '.Text::get('SEARCHBAR_BUTTON_DETAILS').'
                            </a>
                        </div>
                        <div id="search_body" class="transition">
                            <div id="search_type" class="search_detail_box">
                                <label class="form_label"><span>'.Text::get('SEARCHBAR_LABEL_DETAILS_TYPE').'</span></label>
                                <input type="checkbox" name="search_offers" id="search_offer" value="1"'.$searchOffers.'>
                                <label for="search_offer">'.Text::get('SEARCHBAR_LABEL_DETAILS_OFFER').'</label>
                                <input type="checkbox" name="search_requests" id="search_request" value="1"'.$searchRequests.'>
                                <label for="search_request">'.Text::get('SEARCHBAR_LABEL_DETAILS_REQUEST').'</label>
                            </div>
                            <div id="search_zip" class="search_detail_box">
                                <label class="form_label"><span>'.Text::get('SEARCHBAR_LABEL_DETAILS_PLATTFORM').'</span></label>
                                <input type="checkbox" name="search_intern" id="search_intern" value="1"'.$searchInternal.'>
                                <label for="search_intern">'.Text::get('SEARCHBAR_LABEL_DETAILS_INTERN').'</label>
                                <input type="checkbox" name="search_extern" id="search_extern" value="1"'.$searchExternal.'>
                                <label for="search_extern">'.Text::get('SEARCHBAR_LABEL_DETAILS_EXTERN').'</label>
                            </div>
                            <div class="clear"></div>
                        </div>
                        <input type="hidden" name="custom_search" value="1">
                        <input type="submit" value="'.Text::get('SEARCHBAR_BUTTON_SAVE').'" id="search_details_submit" name="" class="button">
                    </div>';
                }
            echo '
            </form>
        </div>
        <div class="clear"></div>
        ';
    }

    public static function showPagination($number_results=0, $howMany='', $prev='', $next='', $show_pages = true)
    {
        $page = PA::getPageNumber();
        if (is_int($howMany)) {
            $ppp = $howMany;
        } else {
            $ppp = Config::get('PPP');
        }
        $pages = ceil($number_results / $ppp);
        $prev_page = $page-1;
        $next_page = $page+1;
        $currentURL = Helper::getCurrentURL();
        $prev_link = $currentURL.'/page/'.$prev_page;
        $next_link = $currentURL.'/page/'.$next_page;
        if ($number_results > $ppp) {
            echo '
            <div class="pagination_box">';
                if ($page > 1) {
                    echo '
                    <a href="'.$prev_link.'">
                        <div class="pagination_prev">
                            <div class="pagination_prev_icon"></div>';
                            if ($prev) {
                                echo '<div class="pagination_prev_text">'.$prev.'</div>';
                            }
                        echo '
                        </div>
                    </a>';
                }
                if ($page < $pages) {
                echo '
                <a href="'.$next_link.'">
                    <div class="pagination_next">
                        <div class="pagination_next_icon"></div>';
                        if ($next) {
                            echo '<div class="pagination_next_text">'.$next.'</div>';
                        }
                    echo '
                    </div>
                </a>';
                }
                if ($show_pages == true) {
                echo '
                <div class="pagination_pages">
                    '.$page.' von '.$pages.'
                </div>';
                }
                echo '
                <div class="clear"></div>
            </div>
            <div class="clear"></div>
            ';
        }
    }

    public static function getUnits()
    {
        $all_units = Text::get('UNITS');
        $show_units = Text::get('SHOW_UNITS');
        $accent_units = Text::get('ACCENT_UNITS');

        $units = array(
            "units_show" => $show_units,
            "units_all" => $all_units,
            "units_accent" => $accent_units
        );
        return $units;
    }

    public static function showUnitsDropdown($data, $selected='', $type='')
    {
        if ($type == 'short') {
            $type = 1;
        } else {
            $type = 0;
        }

        echo '
        <select id="offerUnits"
                class="form_element"
                name="offerUnit">';

        foreach($data['units_show'] as $id)
        {
            echo '
            <option value="'.$id.'" class="unit_option ';
            if (in_array($id,$data['units_accent'])) {
                echo 'unit_accent';
            }
            echo '"';
            if ($selected == $id) { echo ' selected'; }
            echo '>';
            echo $data['units_all'][$id][$type];
            echo '
            </option>';
        }

        echo '
        </select>
        ';
    }

    public static function getCurrencies()
    {
        $all_currency       = Text::get('CURRENCY');
        $show_currencies    = Text::get('SHOW_CURRENCIES');

        $currency = array(
            "currency_show" => $show_currencies,
            "currency_all"  => $all_currency
        );
        return $currency;
    }

    public static function showCurrencyDropdown($data, $selected='', $type='')
    {
        if ($type == 'short') {
            $type = 1;
        } else {
            $type = 0;
        }

        echo '
        <select id="offerCurrency"
                class="form_element"
                name="offerCurrency">';

        foreach($data['currency_show'] as $id) {
            echo '
            <option value="'.$id.'" class="unit_option"';
            if ($selected == $id) { echo ' selected'; }
            echo '>';
            echo $data['currency_all'][$id][$type];
            echo '
            </option>';
        }

        echo '
        </select>
        ';
    }

    public static function getImageURL($separator = "")
    {
        if ($separator == 'core') {
            return Theme::get('URL').'admin/img';
        } else {
            return PA::getBaseURL().'data/';
        }
    }

    public static function getDistance ($zip_to_object = '')
    {
        if ($zip_to_object == '' && !Session::get('search_plz')) {
            return false;
        } else {
            $zip_from_object = Session::get('search_plz');
            $earthRadius = 6371000;
            $placeFrom = PlaceModel::getPlaceByPostalcode($zip_from_object);
            if (!$placeFrom) {
                return false;
            }
            $latitudeFrom = PA::formatGeoCoordinate($placeFrom->lat);
            $longitudeFrom = PA::formatGeoCoordinate($placeFrom->lon);

            $placeTo = PlaceModel::getPlaceByPostalcode($zip_to_object);
            if (!$placeTo) {
                return false;
            }
            $latitudeTo = PA::formatGeoCoordinate($placeTo->lat);
            $longitudeTo = PA::formatGeoCoordinate($placeTo->lon);

            // convert from degrees to radians
            $latFrom = deg2rad($latitudeFrom);
            $lonFrom = deg2rad($longitudeFrom);
            $latTo = deg2rad($latitudeTo);
            $lonTo = deg2rad($longitudeTo);

            $lonDelta = $lonTo - $lonFrom;
            $a = pow(cos($latTo) * sin($lonDelta), 2) +
            pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2);
            $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta);

            $angle = atan2(sqrt($a), $b);
            $result = round(($angle * $earthRadius) / 1000,2);

            return $result;
        }
    }

    public static function formatGeoCoordinate($coordinate)
    {
        $coordinate = (float) $coordinate;
        $coordinate = $coordinate/1000000;
        return $coordinate;
    }

    public static function showDistanceBox($distance = '',$unit = 'Km')
    {
        if ($distance === false || $distance === '') {
            $showDistance = Text::get('OFFER_DISTANCE_NOT_AVAILABLE');
        } else {
            if (isset($distance) && is_float($distance) && $distance > 0) {
                $showDistance = $distance.' '.$unit;
            } elseif ($distance < 3) {
                $showDistance = Text::get('OFFER_DISTANCE_CLOSE_BY');
            }
        }
        echo '
        <div id="distance">
            <a href="#distance">
                <div id="distance_edit_button"></div>
            </a>
            <div class="offer_label">
            '.Text::get('OFFER_DISTANCE').':
            </div>
            '.$showDistance.'*
            <div id="offer_dates">
                *'.Text::get('OFFER_DISTANCE_BEE_LINED').'
            </div>

            <div id="distance_edit" class="transition">
                <form method="post" action="'.PA::getURL().'update/postalcode/'.Helper::getCurrentPath().'">
                    <input type="number" class="form_element" id="distance_edit_input" name="setNewPLZ" value="'.Session::get('search_plz').'">
                    <input type="submit" id="distance_edit_submit" value="">
                </form>
            </div>
        </div>
        ';
    }

    public static function getHomeURL()
    {
        return Config::getURL();
    }

    public static function getBaseURL()
    {
        return Config::get('URL');
    }

    public static function getURL()
    {
        return Config::getURL();
    }

    public static function getThemeURL()
    {
        return Theme::get('URL');
    }

    public static function getThemeName()
    {
        return Theme::get('NAME');
    }

    public static function getPictureURL($path, $size, $type)
    {
        $image_parts = explode(":", $path);

        $image_path = PA::getImageURL().$image_parts[0].$type.'_'.$size.$image_parts[1];
        return $image_path;
    }

    public static function getRandomFeaturedOffers($args)
    {
        return OfferModel::getFeaturedOffers($args);
    }

    public static function getOffers($args)
    {
        return OfferModel::getOffers($args);
    }

    public static function getRandomFeaturedProfiles($args)
    {
        return UserProfileModel::getRandomFeaturedProfiles($args);
    }

    public static function getProfiles($args)
    {
        return UserProfileModel::getProfiles($args);
    }

    public static function getThemes()
    {
        return Theme::getThemes();
    }

    public static function isLoggedIn()
    {
        return Session::userIsLoggedIn();
    }

    public static function isSuperAdmin()
    {
        return Session::userIsSuperAdmin();
    }

    public static function isAdmin()
    {
        return Session::userIsAdmin();
    }

    public static function isUser()
    {
        return true;
    }

    public static function isOfferPage()
    {
        $offerTypes = array('offer','editOffer','addOffer');
        return (in_array(View::getTheFilename(), $offerTypes) ? true : false);
    }

    public static function isProfilePage()
    {
        $userTypes = array('profile','editProfile','ownProfile');
        return (in_array(View::getTheFilename(), $userTypes) ? true : false);
    }

    public static function isPage()
    {
        return (View::getTheFilename() == 'page' ? true : false);
    }

    public static function getPageNumber()
    {
        return DatabaseArgs::getPageNumber();
    }

    public static function isFirstPage()
    {
        if (in_array(DatabaseArgs::getPageNumber(),array(1,''))) {
            return true;
        } else {
            return false;
        }
    }

    public static function isEditable()
    {
        if (PA::isOfferPage() == true ||
            PA::isPage() == true ||
            PA::isProfilePage() == true) {
            if ((View::get('user_id') == Session::get('user_id')) || PA::isAdmin()) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public static function getEditLink($type, $id)
    {
        return PA::getLink($type, $id);
    }

    public static function showContact($text = '', $link = '', $class = '')
    {
        if ($text && $link) {
            $more = '<a href="'.$link.'"><div class="button">'.$text.'</div></a>';
        } else {
            if (Config::getFromDB('MarketContactLink') != 0) {
                $contactPage = PageModel::getPage(Config::getFromDB('MarketContactLink'));
                $link = PA::getLink('page', $contactPage->slug);
                $text = Config::getFromDB('MarketContactLinkText');
                $more = '<a href="'.$link.'"><div class="button">'.$text.'</div></a>';
            } else {
                $more = '';
            }
        }

        $marketName = Helper::cleanForOutput(Config::getFromDB('MarketName'));
        $marketContactPerson = Helper::cleanForOutput(Config::getFromDB('MarketContactPerson'));
        if ($marketContactPerson != '') {
            $showContactPerson = $marketContactPerson.'<br>';
        } else {
            $showContactPerson = '';
        }
        $marketAddressStreet = Helper::cleanForOutput(Config::getFromDB('MarketAddressStreet'));
        $marketAddressStreetNo = Helper::cleanForOutput(Config::getFromDB('MarketAddressNumber'));
        if ($marketAddressStreet != '') {
            $showAddressStreet = $marketAddressStreet.' '.$marketAddressStreetNo.'<br>';
        } else {
            $showAddressStreet = '';
        }
        $marketAddressZipcode = Helper::cleanForOutput(Config::getFromDB('MarketAddressZipcode'));
        if ($marketAddressZipcode != '') {
            $showAddressCodeAndCity = $marketAddressZipcode.' ';
        } else {
            $showAddressCodeAndCity = '';
        }
        $marketAddressCity = Helper::cleanForOutput(Config::getFromDB('MarketAddressCity'));
        if ($marketAddressCity != '') {
            $showAddressCodeAndCity .= $marketAddressCity.'<br>';
        } else {
            $showAddressCodeAndCity .= '<br>';
        }
        $marketContactTel = Helper::cleanForOutput(Config::getFromDB('MarketContactTel'));
        if ($marketContactTel != '') {
            $showContactTel = 'Telefon: '.$marketContactTel.'<br>';
        } else {
            $showContactTel = '';
        }
        $marketContactFax = Helper::cleanForOutput(Config::getFromDB('MarketContactFax'));
        if ($marketContactFax != '') {
            $showContactFax = 'Telefax: '.$marketContactFax.'<br>';
        } else {
            $showContactFax = '';
        }
        $email = Helper::cleanForOutput(Config::getFromDB('MarketContactEmail'));
        echo '
            <div id="plattform_contact" class="'.$class.'">
                <p>
                    <strong>'.$marketName.'</strong><br>
                    '.$showContactPerson.'
                    '.$showAddressStreet.'
                    '.$showAddressCodeAndCity.'<br>';
                    if ($email != '') { PA::showEmail($email); echo '<br>'; }
                    echo '
                    '.$showContactTel.'
                    '.$showContactFax.'
                </p>
                    '.$more.'
            </div>
        ';
    }

    public static function getAboutText($type='')
    {
        if ($type == 'long') {
            return Helper::cleanForOutput(Config::getFromDB('MarketDetail'));
        } else {
            return Helper::cleanForOutput(Config::getFromDB('MarketDetailShort'));
        }
    }

    public static function showAbout($text = '', $link = '', $class = '')
    {
        if ($text && $link) {
            $more = '<a href="'.$link.'"><div class="button">'.$text.'</div></a>';
        } else {
            if (Config::getFromDB('MarketDetailLink') != 0) {
                $aboutPage = PageModel::getPage(Config::getFromDB('MarketDetailLink'));
                $link = PA::getLink('page', $aboutPage->slug);
                $text = Config::getFromDB('MarketDetailLinkText');
                $more = '<a href="'.$link.'"><div class="button">'.$text.'</div></a>';
            } else {
                $more = '';
            }
        }

        $short_about = PA::getAboutText();

        echo '
            <div id="plattform_about" class="'.$class.'">';
                if ($short_about != '') {
                    echo '
                <strong>'.$short_about.'</strong><br><br>';
                }
                echo PA::getAboutText('long').'
                '.$more.'
            </div>
        ';
    }

    public static function showLoginForm($class = '')
    {
        echo '
        <div id="login_box" class="'.$class.'">
            <h2>'.Text::get('LOGIN_HEADLINE').'</h2>
            <form method="post" action="'.PA::getURL().'login/login" id="login_form">
                <input type="text"
                       name="user_name"
                       class="form_element"
                       placeholder="'.Text::get('LOGIN_INPUT_PLACEHOLDER_USERNAME').'"
                       id="login_input_username">
                <input type="password"
                       name="user_password"
                       class="form_element"
                       placeholder="'.Text::get('LOGIN_INPUT_PLACEHOLDER_PASSWORD').'"
                       id="login_input_password">';
        if (Request::get('redirect')) {
            echo '<input type="hidden" name="redirect" value="'.Request::get('redirect').'">';
        }
        echo '
                <input type="submit" value="'.Text::get('LOGIN_SUBMIT_VALUE').'" id="login_submit" class="form_submit">
            </form>
            <div class="login_newpw_button">
                <a href="'.PA::getURL().'login/requestPasswordReset">'.Text::get('LOGIN_NEWPW').'</a>
            </div>
        </div>';
    }

    public static function showRegisterForm($registration, $class = '')
    {
        echo '
        <div id="login_box" class="'.$class.'">';
        if (Text::get('REGISTER_HEADLINE') != '') {
            echo '<h2>'.Text::get('REGISTER_HEADLINE').'</h2>';
        }

        if (empty($registration)) {
            $registration = new stdClass();
            $registration->user_name = '';
            $registration->user_email = '';
            $registration->user_password_new = '';
            $registration->user_password_repeat = '';
        }
        echo '
        <form method="post" action="'.PA::getURL().'register/register_action" id="login_form">
            <input type="text"
                   pattern="[a-zA-Z0-9]{2,64}"
                   name="user_name"
                   class="form_element"
                   placeholder="'.Text::get('REGISTER_INPUT_PLACEHOLDER_USERNAME').'"
                   value="'.$registration->user_name.'"
                   required />
            <input type="email"
                   name="user_email"
                   class="form_element"
                   placeholder="'.Text::get('REGISTER_INPUT_PLACEHOLDER_EMAIL').'"
                   value="'.$registration->user_email.'"
                   required />
            <input type="password"
                   name="user_password_new"
                   class="form_element"
                   pattern=".{6,}"
                   placeholder="'.Text::get('REGISTER_INPUT_PLACEHOLDER_PASSWORD').'"
                   value="'.$registration->user_password_new.'"
                   autocomplete="off"
                   required />
            <input type="password"
                   name="user_password_repeat"
                   class="form_element"
                   pattern=".{6,}"
                   placeholder="'.Text::get('REGISTER_INPUT_PLACEHOLDER_PASSWORD2').'"
                   value="'.$registration->user_password_repeat.'"
                   autocomplete="off"
                   required />';

            if (Text::get('ARE_YOU_HUMAN') !='') {
                echo '<h2>'.Text::get('ARE_YOU_HUMAN').'</h2>';
            }
            echo '
            <div id="captcha_box">
                <img id="captcha" src="'.PA::getURL().'login/showCaptcha">'; ?>
                <a href="#" onclick="document.getElementById('captcha').src = '<?php echo Config::getURL(); ?>login/showCaptcha?' + Math.random(); return false" id="new_captcha">
                    <?php echo Text::get('NEW_CAPTCHA').'
                </a>
            </div>
            <input type="text"
                   name="captcha"
                   class="form_element"
                   placeholder="'.Text::get('REGISTER_INPUT_PLACEHOLDER_CAPTCHA').'"
                   required />

            <input type="submit" value="'.Text::get('REGISTER_SUBMIT_VALUE').'" id="login_submit" class="form_submit">
        </form>
        </div>';
    }

    public static function getSettingsFromDB($key='')
    {
        if ($key == '') {
            return false;
        }

        return Config::getFromDB($key);
    }

    public static function getRegisterStatus()
    {
        return PA::getSettingsFromDB('MarketRegistrationStatus');
    }

    public static function showOfferDates($created,$modified)
    {
        $created = strtotime($created);
        $modified = strtotime($modified);
        $diff = 86400;
        $difference = $modified - $created;

        if ($difference > $diff) {
            echo 'Erstellt am: '.date('d.m.Y', $created).' Geändert am: '.date('d.m.Y', $modified);
        } else {
            echo 'Erstellt am: '.date('d.m.Y', $created);
        }
    }

    public static function showOffersWithPictures($offers, $showTotalNumbers = true)
    {
        if ($offers['offers'] == 0) {
            return false;
        }

        $a = 1;
        echo '<div class="offerlist_feature_box clear">';
        if ($showTotalNumbers === true) {
            $a = 2;
            $textTotalNumber = PA::filter(Text::get("OFFERS_TOTAL_NUMBER"),
                                          Helper::getTotalNumberByType(1));
            $link = Config::getURL() . 'offers';
            echo '
            <a href="'.$link.'">
                <div class="offerlist_feature offerlist_feature_total">
                    <h3>'.$textTotalNumber.'</h3>
                    <div class="offerlist_feature_show_all">'
                        .Text::get("OFFERS_SHOW_ALL")
                    .'</div>
                </div>
            </a>';
        }

        foreach ($offers['offers'] as $offer) {
            $extraclass = '';
            if ($a % 2 == 0) { $extraclass = 'offerlist_feature_2n'; }
            if ($a % 4 == 0) { $extraclass = 'offerlist_feature_2n offerlist_feature_4n'; }

            $offer_price = Helper::convertPrice($offer->price,
                                                $offer->currency,
                                                $offer->unit,
                                                'short');

            $link = PA::getLink('offer', $offer->slug);
            echo '
            <div class="offerlist_feature '.$extraclass.'"';
            if ($offer->image) {
                echo ' style="background-image:';
                echo "url('"; echo PA::getPictureURL($offer->image,'small','offer'); echo"');".'"';
            }
            echo '>
            <a href="'.$link.'" title="'.Helper::cleanForOutput($offer->title).'">
                <h4>'.Helper::cleanForOutput($offer->title).'</h4>';
                if ($offer->price) {
                    echo '
                    <div class="offerlist_feature_price">
                        '.$offer_price['price'].$offer_price['currency'].$offer_price['unit'].
                    '</div>';
                }
                echo '
                    </a>
                </div>';
            $a++;
        }
        echo '<div class="clear"></div>';
        echo '</div>';
    }

    public static function showOfferList($offers, $headlines = '', $date = true, $showdist = true, $sort = true, $showextern = true, $showSortbar = true)
    {
        if ($offers['number'] == 0 || !isset($offers['number'])) {
            echo '<h2 class="feedback error">'.Text::get('OFFERLIST_NO_RESULT').'</h2>';
            return false;
        }

        if ($headlines != '') {
            PA::showHeadline('h2',$headlines['offers'],'icn_offer_black.png','');
        }
        PA::generateOfferList($offers['offers'], $date, $showdist, $sort, $showextern, $showSortbar);

        if (isset($offers['requests']) && $offers['numberRequests'] > 0) {
            if ($headlines != '') {
                PA::showHeadline('h2',$headlines['requests'],'icn_request_black.png','');
            }
            PA::generateOfferList($offers['requests'], $date, $showdist, $sort, $showextern, $showSortbar);
        }
    }

    public static function generateOfferList($offers, $date, $showdist, $sort, $showextern, $showSortbar)
    {
        $all_units = Text::get('UNITS');
        $currencies = PA::getCurrencies();
        $currencies = $currencies['currency_all'];

        $sortStmt = DatabaseArgs::getOrderBy();
        $sortArgs = explode(' ',$sortStmt);

        if ($sortArgs[0] == 'title' && $sortArgs[1] == 'ASC') {
            $sortTitleToggel = 'DESC';
        } else {
            $sortTitleToggel = 'ASC';
        }

        $sortTitleLink = Helper::getCurrentURL().'/sort/title/'.$sortTitleToggel;

        if ($sortArgs[0] == 'modified' && $sortArgs[1] == 'ASC') {
            $sortDistanceToggel = 'DESC';
        } else {
            $sortDistanceToggel = 'ASC';
        }

        $sortModifiedLink = Helper::getCurrentURL().'/sort/modified/'.$sortDistanceToggel;

        if ($sortArgs[0] == 'distance' && $sortArgs[1] == 'ASC') {
            $sortDistanceToggel = 'DESC';
        } else {
            $sortDistanceToggel = 'ASC';
        }

        $sortDistanceLink = Helper::getCurrentURL().'/sort/distance/'.$sortDistanceToggel;

        if ($sortArgs[0] == 'price' && $sortArgs[1] == 'ASC') {
            $sortPriceToggel = 'DESC';
        } else {
            $sortPriceToggel = 'ASC';
        }

        $sortPriceLink = Helper::getCurrentURL().'/sort/price/'.$sortPriceToggel;

        if (Session::get('search_plz') && $showdist === true) {
            $dist = true;
        } else {
            $dist = false;
        }

        echo '
        <div class="offerlist_table ';
            if ($dist === true) {
                echo 'table_distance ';
            }

            if ($date === true) {
                echo 'table_date ';
            }

            if ($date === true && $dist === true) {
                echo 'table_both';
            }

            echo '">';
        if ($showSortbar === true) {
            echo '
                <div class="offerlist_table_head">
                    <div class="offerlist_table_th table_col1';

                    if ($showextern === true) {
                        echo ' list_wherefrom';
                    }

                    echo '">'.Text::get('OFFERLIST_OFFER').'';

                    if ($sort === true) {
                        echo '
                        <a href="'.$sortTitleLink.'">
                            <div class="offerlist_table_sort ';
                            if ($sortArgs[0] == 'title' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                            elseif ($sortArgs[0] == 'title' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                        echo '"></div>
                        </a>';
                    }

                    echo '
                    </div>';

                    if ($date === true) {
                        echo '
                        <div class="offerlist_table_th  table_col2">'.Text::get('OFFERLIST_DATE').'';

                        if ($sort === true) {
                            echo '
                            <a href="'.$sortModifiedLink.'">
                                <div class="offerlist_table_sort ';
                                if ($sortArgs[0] == 'modified' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                                elseif ($sortArgs[0] == 'modified' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                            echo '"></div>
                            </a>';
                        }
                        echo '
                        </div>';
                    }

                    if ($dist === true) {
                        echo '
                        <div class="offerlist_table_th  table_col3">'.Text::get('OFFERLIST_DISTANCE').'';

                        if ($sort === true) {
                            echo '
                            <a href="'.$sortDistanceLink.'">
                                <div class="offerlist_table_sort ';
                                if ($sortArgs[0] == 'distance' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                                elseif ($sortArgs[0] == 'distance' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                            echo '"></div>
                            </a>';
                        }

                        echo '
                        </div>';
                    }

                    echo '
                    <div class="offerlist_table_th  table_col4">'.Text::get('OFFERLIST_PRICE').'';
                    if ($sort === true) {
                        echo '
                        <a href="'.$sortPriceLink.'">
                            <div class="offerlist_table_sort ';
                            if ($sortArgs[0] == 'price' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                            elseif ($sortArgs[0] == 'price' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                        echo '"></div>
                        </a>';
                    }
                    echo '
                    </div>
                <div class="clear"></div>
            </div>
            ';
        }

        foreach ($offers as $offer) {
            $offer_name = Helper::cleanForOutput($offer->title);
            $offer_date = $offer->modified;
            $offer_distance = $offer->distance;

            $offer_price = Helper::convertPrice($offer->price,
                                                $offer->currency,
                                                $offer->unit,
                                                'short');

            if ($offer->external == 1) {
                $offer_link = $offer->external_url.'" target="_blank';
                $isextern = true;
            } else {
                $offer_link = PA::getLink('offer', $offer->slug);
                $isextern = false;
            }
            echo '
            <div class="offerlist_table_row">
                <a href="'.$offer_link.'">
                    <div class="offerlist_table_tc table_col1';
                    if ($showextern === true) {
                        if ($isextern === true) {
                            echo ' list_extern';
                        } else {
                            echo ' list_intern';
                        }
                    }
                    echo '">';
                    echo $offer_name.'</div>';
                    if ($date === true) {
                        echo '<div class="offerlist_table_tc table_col2">'
                            .date('d.m.Y',strtotime($offer_date)).'</div>';
                    }
                    if ($dist === true) {
                        echo '
                        <div class="offerlist_table_tc table_col3">'.$offer_distance.'</div>';
                    }

                    echo '
                    <div class="offerlist_table_tc table_col4">
                        <div class="table_col4_1 ';
                        if($offer_price['currency']==''){echo'offerlist_nocur';}
                        echo'">
                            '.$offer_price['price'].$offer_price['currency'].'
                        </div>
                        <div class="table_col4_2 ';
                        if($offer_price['currency']==''){echo'offerlist_nocur';}
                        echo'">
                            '.$offer_price['unit'].'
                        </div>
                    </div>
                    <div class="clear"></div>
                </a>
            </div>
            ';
        }
        echo '
        </div>';
    }

    public static function generateUserList($users, $showdist, $sort)
    {
        $sortStmt = DatabaseArgs::getOrderBy();
        $sortArgs = explode(' ',$sortStmt);

        if ($sortArgs[0] == 'company_name' && $sortArgs[1] == 'ASC') {
            $sortTitleToggel = 'DESC';
        } else {
            $sortTitleToggel = 'ASC';
        }
        $sortTitleLink = Helper::getCurrentURL().'/sort/company_name/'.$sortTitleToggel;

        if ($sortArgs[0] == 'company_address_zipcode' && $sortArgs[1] == 'ASC') {
            $sortDistanceToggel = 'DESC';
        } else {
            $sortDistanceToggel = 'ASC';
        }
        $sortModifiedLink = Helper::getCurrentURL().'/sort/company_address_zipcode/'.$sortDistanceToggel;

        if ($sortArgs[0] == 'company_address_city' && $sortArgs[1] == 'ASC') {
            $sortPriceToggel = 'DESC';
        } else {
            $sortPriceToggel = 'ASC';
        }
        $sortPriceLink = Helper::getCurrentURL().'/sort/company_address_city/'.$sortPriceToggel;

        if (Session::get('company_address_city') && $showdist === true) {
            $dist = true;
        } else {
            $dist = false;
        }

        echo '
        <div class="userlist_table ';
            if ($dist === true) {
                echo 'table_distance ';
            }

                echo 'table_date ';

//            if ($date === true && $dist === true) {
//                echo 'table_both';
//            }

            echo '">
            <div class="userlist_table_head">
                <div class="userlist_table_th table_col1';

                echo '">'.Text::get('USER').'';

                if ($sort === true) {
                    echo '
                    <a href="'.$sortTitleLink.'">
                        <div class="userlist_table_sort ';
                        if ($sortArgs[0] == 'company_name' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                        elseif ($sortArgs[0] == 'company_name' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                    echo '"></div>
                    </a>';
                }

                echo '
                </div>';

                    echo '
                    <div class="userlist_table_th  table_col2">'.Text::get('USER_ZIP').'';

                    if ($sort === true) {
                        echo '
                        <a href="'.$sortModifiedLink.'">
                            <div class="userlist_table_sort ';
                            if ($sortArgs[0] == 'company_address_zipcode' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                            elseif ($sortArgs[0] == 'company_address_zipcode' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                        echo '"></div>
                        </a>';
                    }
                    echo '
                    </div>';

                if ($dist === true) {
                    echo '
                    <div class="userlist_table_th  table_col3">'.Text::get('OFFERLIST_DISTANCE').'';

                    if ($sort === true) {
                        echo '
                        <a href="'.$sortDistanceLink.'">
                            <div class="userlist_table_sort ';
                            if ($sortArgs[0] == 'distance' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                            elseif ($sortArgs[0] == 'distance' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                        echo '"></div>
                        </a>';
                    }

                    echo '
                    </div>';
                }

                echo '
                <div class="userlist_table_th table_col4">'.Text::get('USER_LOCATION').'';
                if ($sort === true) {
                    echo '
                    <a href="'.$sortPriceLink.'">
                        <div class="userlist_table_sort ';
                        if ($sortArgs[0] == 'company_address_city' && $sortArgs[1] == 'DESC') { echo 'sort_down'; }
                        elseif ($sortArgs[0] == 'company_address_city' && $sortArgs[1] == 'ASC') { echo 'sort_up'; }
                    echo '"></div>
                    </a>';
                }
                echo '
                </div>
            <div class="clear"></div>
        </div>
        ';
        foreach ($users as $user) {

            $user_name          = Helper::cleanForOutput($user->company_name);
            $user_claim         = ' - '.Helper::cleanForOutput($user->company_claim);
            $user_link          = PA::getLink('user', $user->slug);

            echo '
            <div class="userlist_table_row">
                <a href="'.$user_link.'">
                    <div class="userlist_table_tc table_col1';

                    echo '">';
                    echo $user_name.'<span class="userlist_claim">'.$user_claim.'</span>&nbsp;</div>';
                        echo '<div class="userlist_table_tc table_col2">'
                            .$user->zipcode.'&nbsp;</div>';
                    if ($dist === true) {
                        echo '
                        <div class="userlist_table_tc table_col3">'.$offer_distance.'</div>';
                    }

                    echo '
                    <div class="userlist_table_tc table_col4">
                            '.$user->city.'&nbsp;
                    </div>
                    <div class="clear"></div>
                </a>
            </div>
            ';
        }
        echo '
        </div>';
    }

    public static function getLink($type, $id = '')
    {
        switch ($type) {
            case 'login':
                $path = 'login';
                break;
            case 'pages':
                $path = 'pages';
                break;
            case 'logout':
                $path = 'profiles/logout';
                break;
            case 'profile':
                $path = 'profiles';
                break;
            case 'register':
                $path = 'register';
                break;
            case 'offer':
                $path = 'offers/view';
                break;
            case 'offers':
                $path = 'offers';
                break;
            case 'requests':
                $path = 'offers/requests';
                break;
            case 'newOffer':
                $path = 'offers/add';
                break;
            case 'user':
                $path = 'profiles/view';
                break;
            case 'editUser':
                $path = 'profiles/edit';
                break;
            case 'editOffer':
                $path = 'offers/edit';
                break;
            case 'editPage':
                $path = 'pages/edit';
                break;
            case 'editOwnProfile':
                $path = 'profiles/edit';
                break;
            case 'changePassword':
                $path = 'profiles/changePassword';
                break;
            case 'viewOwnProfile':
                $path = 'profiles/view_own';
                break;
            case 'page':
                $path = 'pages/view';
                break;
            case 'feature_offer_user':
                $path = 'update/feature/user/offer';
                break;
            case 'feature_offer_admin':
                $path = 'update/feature/admin/offer';
                break;
            case 'delete_offer':
                $path = 'update/delete/offer';
                break;
            case 'delete_profile':
                $path = 'update/delete/profile';
                break;
            case 'delete_image':
                $path = 'update/delete/image';
                break;
            case 'all_users_other':
                $path = 'profiles/gastronomy';
                break;
            case 'all_users':
                $path = 'profiles/all';
                break;
        }
        return Config::getURL() . $path . '/' . $id;
    }

    public static function showFeaturedUsers($user_data)
    {
        echo '
        <div class="userlist_feature_box">';
        $a = 1;
        foreach($user_data['data'] as $users_data) {
            $extraclass = '';
            if ($a == 1) { $extraclass= ' userlist_feature_user_1st'; }
            if ($a % 2 == 0) { $extraclass= ' userlist_feature_user_2n'; }
            if ($a % 4 == 0) { $extraclass= ' userlist_feature_user_2n userlist_feature_user_4n'; }
            echo '
            <div class="userlist_feature_user'.$extraclass.'" ';

            if ($users_data->header_path) {
                echo 'style="background-image:';
                echo "url('";
                echo PA::getPictureURL($users_data->header_path,'medium','header');
                echo "');".'"';
            }
            echo '>';
            if ($users_data->other_featured == 1) {
                echo'<div class="userlist_other_featured_user"></div>';
            }

            echo'
                <a href="'.PA::getLink('user',$users_data->slug).'" title="'
                    .Helper::cleanForOutput($users_data->company_name)
                    .' - '.Helper::cleanForOutput($users_data->company_claim).'">
                    <div class="userlist_feature_user_overlay transition">';
                    if ($users_data->logo_path) {
                        echo '<img src="'.PA::getPictureURL($users_data->logo_path,'medium','logo')
                             .'" class="userlist_feature_user_logo" alt="'
                             .Helper::cleanForOutput($users_data->company_name).'">';
                    }
                    echo '
                        <h2>'.Helper::cleanForOutput($users_data->company_name)
                             .' <span>'.$users_data->company_claim.'</span></h2>
                    </div>
                </a>
            </div>';
            $a++;
        }
        echo '
        <div class="clear"></div>
        </div>
        ';
    }

    public static function showAllUsers($user_data,$featured = 1)
    {
        if ($featured == 1) {
            PA::showFeaturedUsers($user_data);
        }
    }

    public static function showEditMenu($data)
    {
        if (PA::isAdmin()) {
            PA::adminShowEditMenu($data);
        } else {
            if (!PA::isLoggedin()) {
                return false;
            } elseif (PA::isLoggedin()) {
                echo '<div id="user_edit_menu">';

                $featuredimg = 'icn_featured.png';
                $featured = false;

                if (PA::isProfilePage()) {
                    $details = $data;
                    $edit_id = $details->id;
                    $profile_id = $details->id;
                    $edit_type = 'editUser';
                } elseif (PA::isOfferPage()) {
                    $details = $data;
                    $offer = $data['offer'];
                    $edit_id = $offer->id;
                    $profile_id = $offer->profile_id;
                    $edit_type = 'editOffer';
                    if ($offer->user_featured == 1) {
                        $featuredimg = 'icn_featured_ok.png';
                        $featured = true;
                    }
                } elseif (PA::isPage()) {
                    $page = $data['page'];
                    $edit_id = $page->id;
                    $edit_type = 'editPage';
                }

                if (PA::isOwner($edit_id)) {

                    //FEATURE OFFER
                    if (PA::isOfferPage()) {
                        $feature_link = PA::getlink('feature_offer_user',$offer->id);
                        if ($featured == true) {
                            $feature_text = Text::get('EDIT_MENU_UNFEATURE_OFFER');
                        } else {
                            $feature_text = Text::get('EDIT_MENU_FEATURE_OFFER');
                        }
                        echo '
                        <ul class="menu">
                            <li>
                                <a href="'.$feature_link.'">
                                    <img src="'.PA::getThemeURL().'img/'.$featuredimg.'" class="menuhead_img" alt="'.$feature_text.'">
                                </a>
                                <ul>
                                    <li>
                                        <a href="'.$feature_link.'">
                                            '.$feature_text.'
                                        </a>
                                    </li>
                                </ul>
                            </li>
                        </ul>';

                    //DELETE PAGE
                    echo '
                    <ul class="menu">
                        <li>
                            <a href="'.PA::getlink('delete_offer',$edit_id).'">
                                <img src="'.PA::getThemeURL().'img/icn_delete.png" class="menuhead_img delete_button" alt="'
                                        .Text::get('EDIT_MENU_DELETE_OFFER').'">
                            </a>
                            <ul>
                                <li>
                                    <a href="'.PA::getEditLink($edit_type,$edit_id).'" class="delete_button" alt="'
                                            .Text::get('EDIT_MENU_DELETE_OFFER').'">
                                        '.Text::get('EDIT_MENU_DELETE_OFFER').'
                                    </a>
                                </li>
                            </ul>
                        </li>
                    </ul>';
                    }

                    //EDIT PAGE
                    if (PA::isOfferPage()) {
                        $edit_text = Text::get('EDIT_MENU_EDIT_OFFER');
                    } elseif (PA::isProfilePage()) {
                        $edit_text = Text::get('EDIT_MENU_EDIT_PROFILE');
                    }

                    echo '
                    <ul class="menu">
                        <li>
                            <a href="'.PA::getEditLink($edit_type,$edit_id).'">
                                <img src="'.PA::getThemeURL().'img/icn_edit.png" class="menuhead_img" alt="'.$edit_text.'"></a>
                            <ul>
                                <li><a href="'.PA::getEditLink($edit_type,$edit_id).'">'.$edit_text.'</a></li>
                            </ul>
                        </li>
                    </ul>';

                    //NEW OFFER FOR USER
                    $link_new_offer = PA::getLink('newOffer',$profile_id);

                    echo '
                        <ul class="menu">
                            <li>
                                <a href="'.$link_new_offer.'">
                                    <img src="'.PA::getThemeURL().'img/icn_new_offer.png" class="menuhead_img" alt="'.Text::get('EDIT_MENU_NEW_OFFER').'">
                                </a>
                                <ul>
                                    <li><a href="'.$link_new_offer.'">'.Text::get('EDIT_MENU_NEW_OFFER').'</a></li>
                                </ul>
                            </li>
                        </ul>';

                    echo '
                        <div class="clear"></div>
                    </div>';
                }
            }
        }
    }

    public static function showUserContact($contactdata)
    {
        if ($contactdata->company_name != '') {
            $companyName = '<strong>'.Helper::cleanForOutput($contactdata->company_name).'</strong><br>';
        } else {
            $companyName = '';
        }
        if ($contactdata->company_contact_person != '') {
            $companyContact = Helper::cleanForOutput($contactdata->company_contact_person).'<br>';
        } else {
            $companyContact = '';
        }
        if ($contactdata->company_address_street != '') {
            $companyAddress = Helper::cleanForOutput($contactdata->company_address_street).' '
                .Helper::cleanForOutput($contactdata->company_address_street_number).'<br>';
        } else {
            $companyAddress = '';
        }
        if ($contactdata->company_address_zipcode != '') {
            $companyPostalcode = Helper::cleanForOutput($contactdata->company_address_zipcode).' ';
        } else {
            $companyPostalcode = '';
        }
        if ($contactdata->company_address_city != '') {
            $companyCity = Helper::cleanForOutput($contactdata->company_address_city).'<br>';
        } else {
            $companyCity = '<br>';
        }
        if ($contactdata->company_address_state != '') {
            $companyState = Helper::cleanForOutput($contactdata->company_address_state).', ';
        } else {
            $companyState = '';
        }
        if ($contactdata->company_address_country != '') {
            $companyCountry = Helper::cleanForOutput($contactdata->company_address_country).'<br>';
        } else {
            $companyCountry = '<br>';
        }
        echo '
        <h3 class="headline">'.Text::get('USER_CONTACT').'</h3>
        <div id="protagonist_adress">
            <p>
                '.$companyName.'
                '.$companyContact.'
                '.$companyAddress.'
                '.$companyPostalcode.$companyCity.'
                '.$companyState.$companyCountry;
                echo '<br>';
                if ($contactdata->company_phone) {
                    echo Text::get('OFFER_TEL').': '.Helper::cleanForOutput($contactdata->company_phone).'<br>';
                }
                if ($contactdata->company_fax) {
                    echo Text::get('OFFER_FAX').': '.Helper::cleanForOutput($contactdata->company_fax).'<br>';
                }
                echo '<br>';
                if ($contactdata->company_website) {
                    echo '<a href="'.$contactdata->company_website.'" target="_blank">'
                         .Helper::cleanForOutput($contactdata->company_website).'</a><br>';
                }
                if ($contactdata->company_email) {
                    PA::showEmail($contactdata->company_email);
                }
                echo '
            </p>
        </div>';
    }

    public static function showUserOpeningHours($contactdata)
    {
        if ($contactdata->company_opening_hours) {
            echo '
            <h3 class="headline">'.Text::get('USER_OPENING_HOURS').'</h3>
            <div id="protagonist_openinghours">
                <p>
                '.Helper::cleanForOutput($contactdata->company_opening_hours).'
                </p>
            </div>
            ';
        }
    }

    public static function showUserMore($contactdata)
    {
        echo '
        <h3 class="headline">'.Text::get('USER_MORE_HEADLINE').'</h3>
        <div id="protagonist_more">
            <p>
                <a href="'.PA::getLink('user',$contactdata->slug).'">'.Text::get('USER_SHOW_PROFILE').'</a>
            </p>
        </div>
        ';
    }


    public static function showEmail($email)
    {
        $character_set = '+-.0123456789@ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'; $key = str_shuffle($character_set); $cipher_text = ''; $id = 'e'.rand(1,999999999); for ($i=0;$i<strlen($email);$i+=1) $cipher_text.= $key[strpos($character_set,$email[$i])]; $script = 'var a="'.$key.'";var b=a.split("").sort().join("");var c="'.$cipher_text.'";var d="";'; $script.= 'for(var e=0;e<c.length;e++)d+=b.charAt(a.indexOf(c.charAt(e)));'; $script.= 'document.getElementById("'.$id.'").innerHTML="<a href=\\"mailto:"+d+"\\">"+d+"</a>"'; $script = "eval(\"".str_replace(array("\\",'"'),array("\\\\",'\"'), $script)."\")"; $script = '<script type="text/javascript">/*<![CDATA[*/'.$script.'/*]]>*/</script>'; echo '<span id="'.$id.'"></span>'.$script;
    }


    public static function showEditor($text = null)
    {
        echo '
            <textarea id="admin_editor" name="pageBody" class="form_element">
                '.$text.'
            </textarea>
        ';
    }


    public static function showUserList($users, $style = 1)
    {
        if ($style == 1) {
            echo '<div class="userlist_box">';
            foreach ($users as $user) {
                $link = PA::getLink('user',$user->slug);

                echo
                    '<a href="'
                        .$link.'" title="'.Helper::cleanForOutput($user->company_name).'">
                        <div class="userlist_item">
                            <div class="userlist_name">'.Helper::cleanForOutput($user->company_name).'</div>
                            <div class="userlist_claim">'.Helper::cleanForOutput($user->company_claim).'</div>
                            <div class="clear"></div>
                        </div>
                    </a>';
            }
            echo '
                </div>';
        } elseif ($style == 2) {
            echo '
                <div class="userlist_box">
                    <ul class="userlist_ul">';
            foreach ($users as $user) {
                $link = PA::getLink('user',$user->slug);

                echo '
                        <li class="userlist_li">
                            <a href="'. $link .'" title="'.Helper::cleanForOutput($user->company_name).'">
                                <div class="userlist_name">'.Helper::cleanForOutput($user->company_name).'</div>
                                <div class="userlist_claim">'.Helper::cleanForOutput($user->company_claim).'</div>
                                <div class="clear"></div>
                            </a>
                        </li>';
            }
            echo '
                    </ul>
                </div>';
        }
    }

    public static function filter($text,$replace_with)
    {
        return preg_replace('/\[REPLACE\]/',$replace_with,$text);
    }

    public static function replace($text,$search,$replace){
        return str_replace($search, $replace, $text);
    }

    public static function formValue($value)
    {
        if ($value == null || !isset($value)) {
            $value = '';
        }
        return $value;
    }

    public static function showFeedback()
    {
        View::renderFeedbackMessages();
    }

    public static function isOwner($id)
    {
        if (PA::isProfilePage()) {
            return UserProfileModel::isOwner($id);
        } elseif (PA::isOfferPage()) {
            return OfferModel::isOwner($id);
        }
    }

    // ADMIN
    public static function adminShowUserList($users)
    {
        return Admin::adminShowUserList($users);
    }

    public static function adminShowEditMenu($data)
    {
        return Admin::adminShowEditMenu($data);
    }

    public static function adminShowOfferList($offers)
    {
        return Admin::adminShowOfferList($offers);
    }

    public static function adminGetLink($type, $id='')
    {
        return Admin::adminGetLink($type, $id);
    }

    public static function getOffersWithProfile($args)
    {
        return OfferModel::getOffersWithProfile($args);
    }

    public static function adminShowPageUsers($users)
    {
        return Admin::adminShowPageUsers($users);
    }

    public static function adminShowPageSettings($settings)
    {
        return Admin::adminShowPageSettings($settings);
    }

    public static function adminShowPagePages($pages)
    {
        return Admin::adminShowPagePages($pages);
    }

    public static function adminShowPagePagesEdit($page)
    {
        return Admin::adminShowPagePagesEdit($page);
    }

    public static function adminShowPageOffers($offers)
    {
        return Admin::adminShowPageOffers($offers);
    }

    public static function ShowCategories($type, $prefix, $selected)
    {
        return Admin::adminShowCategories($type, $prefix, $selected);
    }

    public static function adminShowPageIndex($settings)
    {
        return Admin::adminShowPageIndex($settings);
    }

    public static function isAdminArea()
    {
        return Admin::isAdminArea();
    }

    public static function isExternalOffer($offer)
    {
        if ($offer->external == 1) {
            return true;
        } else {
            return false;
        }
    }

    public static function showExternalPlatform($id)
    {
        $platform = ConnectionsModel::getPlatformDetailsByID($id);
        if ($platform === false) {
            $platform = new stdClass();
            $platform->name = Text::get('PLATFORM_DELETED');
            $platform->deleted_explanation = Text::get('PLATFORM_DELETED_EXPLANATION');
        }
        echo '
        <h3 class="headline external_offer_headline">'.Text::get('USER_EXTERNAL_OFFER').'</h3>
        <div id="protagonist_extern">
            <p>
            '.Text::get('USER_EXTERNAL_OFFER_TEXT').'
            </p>
        </div>
        <h3 class="headline">'.$platform->name.'</h3>
        <div id="protagonist_extern">
            <p>';
                if (isset($platform->deleted_explanation)) {
                    echo $platform->deleted_explanation;
                } else {
                    echo '
                    Ort: '.$platform->location.'<br>
                    Verbunden seit: '.$platform->connected_since.'<br><br>
                    Hier steht eine kurze Beschreibung zu der Plattform. Die sollte in der Regel nicht länger sein, als ein oder zwei Sätze.<br>
                    <a href="'.$platform->url.'" target="_blank">Plattform besuchen</a>';
                }
                echo '
            </p>
        </div>';
    }

    public static function validateInput($fieldName, $emptyMessage, $invalidMessage)
    {
        echo '
        <script>
            var inputName = document.querySelector("input[name=\''.$fieldName.'\']");
            inputName.setCustomValidity("'.$emptyMessage.'");
            inputName.addEventListener("input", function () {
                if (this.value.trim() === "") {
                    this.setCustomValidity("'.$emptyMessage.'");
                } else {
                    this.setCustomValidity("");
                }
            }, false);

            inputName.addEventListener("invalid", function () {
                if (this.value.trim() !== "") {
                    this.setCustomValidity("'.$invalidMessage.'");
                }
            }, false);
        </script>';
    }
}
