<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | PHP version 5                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2012-2013 ARMIA INC                                    |
// +----------------------------------------------------------------------+
// | This source file is a part of iScripts EasyCreate 3.0                 |
//   this file generate a preview for the site that generated by the editor
// +----------------------------------------------------------------------+
// | Authors: jinson<jinson.m@armia.com>                          |
// |                                                                      |
// +----------------------------------------------------------------------+
include "includes/session.php";
include "includes/config.php";
include "includes/function.php";
include "includes/cls_htmlform.php";
include "includes/sitefunctions.php";

include "editor/editor_addwidgetcontent.php";

// Get banner
$createdSiteBanner = getSettingsValue('enable_created_site_banner');
$createdSiteBannerName = getSettingsValue('created_site_banner_name');
$createdSiteBannerLink = getSettingsValue('created_site_banner_link');

$doc = new DOMDocument();
//include "includes/userheader.php";
if (isset($_SESSION['siteDetails'])) {

    // code to find the loading page
    $loadPage = $_GET['page'];
    if ($loadPage != '') {
        foreach ($_SESSION['siteDetails']['pages'] as $pages) {
            if ($pages['link'] == $loadPage)
                $currentPage = $pages['alias'];
        }
    }
    // loading page code ends

    if ($currentPage == '')
        $currentPage = $_SESSION['siteDetails']['currentpage'];


    // hack to update the external app positions
    if ($_SESSION['siteDetails'][$currentPage]['panelpositions']) {
        foreach ($_SESSION['siteDetails'][$currentPage]['panelpositions'] as $key => $panelPositions) {
            if ($key == 'exterbox') {
                //$panelPositions = sort($panelPositions);
                $exterItems = array();
                foreach ($panelPositions as $positions) {
                    if (is_numeric($positions)) {
                        $addPosition = $positions;
                        $exterItems[] = $positions;
                    } else {
                        $exterItems[] = $positions;
                    }
                }
                $_SESSION['siteDetails'][$currentPage]['panelpositions'][$addPosition] = $exterItems;
            }
        }
    }
    // hack ends

    $templateid = $_SESSION['siteDetails']['templateid'];
    $templateThemeId = $_SESSION['siteDetails']['themeid'];
    $templatePath = $_SESSION["session_template_dir"] . "/" . $templateid;

    // code to check whether its a guest book
    $sitePages = $_SESSION['siteDetails']['pages'];
    foreach ($sitePages as $key => $pages) {
        if ($pages['pagetype'] == 'guestbook' && $pages['alias'] == $currentPage)
            $curPageType = 'guestbook';
    }


    // code to get the template details
    $pageTypeId = getPageType($templateid, $currentPage);
    $templateFile = getTemplateFile($templateid, $pageTypeId);
    /*
      if($currentPage == 'index')
      $templateFile   = $_SESSION["session_template_dir"] . "/" . $templateid.'/index_temp.htm';
      else
      $templateFile   = $_SESSION["session_template_dir"] . "/" . $templateid.'/subpage_temp.htm';
     */

    $fh = fopen($templateFile, 'r');
    $theData = fread($fh, filesize($templateFile));
    $theData = str_replace('BASE_URL_REPLACEMENT', './' . $_SESSION["session_template_dir"] . '/' . $templateid . '/', $theData);
    fclose($fh);
    if ($_SESSION['siteDetails'][$currentPage]['panelpositions']) {
        foreach ($_SESSION['siteDetails'][$currentPage]['panelpositions'] as $key => $positions) {

            // get the panel details
            if (is_numeric($key)) {
                $panelDet = mysql_query('select panel_type, temp_id from tbl_template_panel where panel_id=' . $key) or die(mysql_error());
                if (mysql_num_rows($panelDet) > 0) {
                    $rowPanel = mysql_fetch_assoc($panelDet);
                    $replacer = '{$editable' . $rowPanel['panel_type'] . '}';
                    $editedHtml = '';
                    foreach ($positions as $panelPos) {

                        $panelData = $_SESSION['siteDetails'][$currentPage]['panels'][$panelPos];
                        @$doc->loadHTML(mb_convert_encoding($panelData, 'HTML-ENTITIES', 'UTF-8'));

                        // Replacing logo if uploaded from customize site page
                        if ($_SESSION['siteDetails']['siteInfo']['logoName'] != '') {
                            applySiteLogo($_SESSION['siteDetails']['siteInfo']['logoName']);
                        }

                        // Add/Replace company name from customize site page
                        if ($_SESSION['siteDetails']['siteInfo']['companyname'] != '') {
                            applySiteCompany($_SESSION['siteDetails']['siteInfo']['companyname'], $_SESSION['siteDetails']['siteInfo']['compfont'], $_SESSION['siteDetails']['siteInfo']['fntclr'], $_SESSION['siteDetails']['siteInfo']['fontsize']);
                        }

                        // Add/Replace company name from customize site page
                        if ($_SESSION['siteDetails']['siteInfo']['captionname'] != '') {
                            applySiteCaption($_SESSION['siteDetails']['siteInfo']['captionname'], $_SESSION['siteDetails']['siteInfo']['captionfont'], $_SESSION['siteDetails']['siteInfo']['captfntclr'], $_SESSION['siteDetails']['siteInfo']['captionfontsize']);
                        }

                        // Add banner
                        if ($createdSiteBanner && $createdSiteBannerName != '') {
                            applySiteBanner($createdSiteBannerName, $createdSiteBannerLink);
                        }

                        $panelData = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $doc->saveHTML());

                        // finding the template menu details
                        @$doc->loadHTML(mb_convert_encoding($panelData, 'HTML-ENTITIES', 'UTF-8'));
                        $menus = $doc->getElementsByTagName('ul');
                        foreach ($menus as $menu) {
                            if ($menu->getAttribute('data-type') == 'menu') {
                                $menuid = $menu->getAttribute('id');
                                $menuDet = $_SESSION['siteDetails'][$currentPage]['datatypes']['menu'][$menuid]['items'];
                                $menuValue = '<ul id="' . $menuid . '" class="editablemenu" data-type="menu">';
                                foreach ($menuDet as $items) {
                                    $menuValue .= '<li ' . (($currentPage . '.html' == $items['link'] || $currentPage . '.php' == $items['link']) ? 'class="active"' : '') . '  ><a  linkmode="' . $items['linkmode'] . '" href="' . $items['link'] . '">' . $items['title'] . '</a></li>';
                                }
                                //menuValue .= '<a class="jqeditormenusettings" data-param="'.$menuid.'" href="#">Edit Menu</a></ul> ';
                                $pattern = '/<ul (.*?)id="' . $menuid . '"[^:]*<\/ul>/';
                                $panelData = preg_replace($pattern, $menuValue, $panelData);
                            }
                        }
                        $pattern1 = '/<div class="manageMenuStyle"(.*?)[^:]*<\/a><\/div>/';
                        //$pattern1     = '/<a (.*?)class="jqeditormenusettings"[^:]*<\/a>/';
                        $panelData = preg_replace($pattern1, '', $panelData);
                        // finding the template menu details
                        // find the slideshow in the template
                        $divList = $doc->getElementsByTagName('div');
                        foreach ($divList as $divs) {
                            if ($divs->getAttribute('data-type') == 'slider') {
                                $sliderid = $divs->getAttribute('id');
                                //$attributes        = get_object_vars($divs);
                                $pattern = '/<div (.*?)id="' . $sliderid . '"[^~]*<\/div>/';
                                $sliderValue = createSlideShow($sliderid, $attributes);
                                //$sliderValue  = showSlider($sliderid,$currentPage);
                                $panelData = preg_replace($pattern, $sliderValue, $panelData);
                            } else if ($divs->getAttribute('data-type') == 'contactform') {
                                $formData = 'editablecontact_' . $panelPos . '_1';
                                $objForm = new Htmlform();
                                $customFormDetails = $_SESSION['siteDetails'][$currentPage]['apps'][$formData];

                                $editedHtml .= $customFormDetails['formelements'];
                            }
                        }


                        $panelBox = explode('_', $panelPos);

                        if ($panelBox[0] == 'exterbox') { // check that its a widget
                            if ($panelBox[1] == 'navmenu') { // for navigational menu params
                                $menuList = '';
                                $appDetails = $_SESSION['siteDetails'][$currentPage]['apps'][$panelPos]['items'];
                                $appMenuStyle = $_SESSION['siteDetails'][$currentPage]['apps'][$panelPos]['settings']['menutype'];
                                if (sizeof($appDetails) > 0) {
                                    $menuList .= '<div><ul class="' . $appMenuStyle . '">';
                                    foreach ($appDetails as $key => $details) {
                                        $menuList .= '<li><a href="' . $details['link'] . '" target="' . $details['opentype'] . '">' . $details['title'] . '</a></li>';
                                    }
                                    $menuList .= '</ul></div><div class="clear></div>"';
                                }
                                $editedHtml .= $menuList;
                            } else if ($panelBox[1] == 'socialshare') {
                                $appDetails = $_SESSION['siteDetails'][$currentPage]['apps'][$panelPos];

                                $socialShare = '<div>';

                                if (sizeof($appDetails) > 0) {
                                    foreach ($appDetails as $key => $details) {
                                        if ($key == 'twitlink')
                                            $socialShare .= '<a href="' . $details . '"><img src="editor/images/icon_twitter.png" class="socialShareClass"></a>';
                                        else if ($key == 'fppage')
                                            $socialShare .= '<a href="' . $details . '"><img src="editor/images/icon_facebook.png" class="socialShareClass"></a>';
                                        else if ($key == 'linkedinlink')
                                            $socialShare .= '<a href="' . $details . '"><img src="editor/images/icon_linkedin.png" class="socialShareClass"></a>';
                                    }
                                }
                                else
                                    $socialShare .= '<img src="editor/images/icon_facebook.png" class="socialShareClass"> <img src="editor/images/icon_twitter.png" class="socialShareClass"> <img src="editor/images/icon_linkedin.png" class="socialShareClass">';

                                $socialShare .= '</div><div class="clear></div>';
                                $editedHtml .= $socialShare;
                            }
                            else if ($panelBox[1] == 'form') {   // loading the feedback form elements
                                $objForm = new Htmlform();
                                $formDetails = $_SESSION['siteDetails'][$currentPage]['apps'][$panelPos];
                                if (sizeof($formDetails) > 0) {
                                    global $formFeedBackItems;
                                    $feedBackItems = $formDetails['items'];
                                    foreach ($feedBackItems as $key => $items) {
                                        $itemDet = $formFeedBackItems[$items];
                                        $objFormElement = new Formelement();
                                        $objFormElement->type = $itemDet['field'];
                                        $objFormElement->name = $items;
                                        $objFormElement->id = $items;
                                        $objFormElement->label = $itemDet['title'];
                                        $objForm->addElement($objFormElement);
                                    }
                                }
                                $formOutPut = $objForm->renderForm();
                                $editedHtml .= $formOutPut;
                            } elseif ($panelBox[1] == 'htmlbox') {// html widgets
                                $htmlContent = addWidgetContent($_SESSION['siteDetails'][$currentPage]['apps'][$panelPos]);
                                $editedHtml .= $htmlContent;
                            } elseif ($panelBox[1] == 'slider') {
                                $widgetHtml = addWidgetSlider($panelPos, $currentPage);
                                $editedHtml .= $widgetHtml;
                            } elseif ($panelBox[1] == 'googleadsense') {
                                $formDetails = $_SESSION['siteDetails'][$currentPage]['apps'][$panelPos];
                                global $adSenseDimensionsArray;

                                foreach ($adSenseDimensionsArray as $key => $val) {
                                    if ($formDetails['google_ad_dimension'] == $key) {
                                        $width = $val['width'];
                                        $height = $val['height'];
                                    }
                                }
                                $googleAd = addGoogleAd($formDetails['google_ad_slot'], $width, $height, $ad_comment, $formDetails['google_ad_client']);
                                $editedHtml .= $googleAd;
                            } else if ($panelBox[1] == 'dynamicform') {// loading the custom form elements
                                $objForm = new Htmlform();
                                $customFormDetails = $_SESSION['siteDetails'][$currentPage]['apps'][$panelPos];

                                $editedHtml .= $customFormDetails['formelements'];
                            }  //echo "If: "; echopre($editedHtml); echopre("********************************");
                        } else {
                            // code to get the guest book details
                            if ($curPageType == 'guestbook' && $rowPanel['panel_type'] == 'maincontent') {
                                //$guestBookCode = showGuestBookWidgetContent();

                                $guestBookCode = generateGuestBookContentAddCode('', 'preview');
                                $guestBookCode = str_replace("&nbsp;", " <br>", $guestBookCode);
                                $editedHtml .= $guestBookCode;
                            } else {
                                // ------- code to replace the unwanted items-------
                                // $replaceQuery    = ".//a[@class='jqeditormenusettings']";
                                //$editedHtml .= removeItemsUsingDOM($replaceQuery,$panelData);
                                // --------- replace code ends ------------
                                $editedHtml .= $panelData;
                                // $editedHtml .= removeItemsUsingDOM($replaceQuery,$_SESSION['siteDetails'][$currentPage]['panels'][$panelPos]);
                            }
                            //echo "Else: ";  echopre($editedHtml); echopre("++++++++++++++++++++++++++++++++++");
                        }
                    }

                    $theData = str_replace($replacer, $editedHtml, $theData);

                    if (stristr($theData, '"images/logo.png"') || stristr($theData, "'images/logo.png'")) {
                        $theData = str_replace('"images/logo.png"', '"' . BASE_URL . 'templates/' . $rowPanel['temp_id'] . '/images/logo.png"', $theData);
                        $theData = str_replace("'images/logo.png'", "'" . BASE_URL . 'templates/' . $rowPanel['temp_id'] . "/images/logo.png'", $theData);
                    }
                }
            }
        }
    }

    // add the theme style to the template
    $theData = changeSiteStyle($templateid, $templateThemeId, $theData);

    //Apply Site color/Page title/Meta Description/Meta Keywords
    if ($_SESSION['siteDetails']['siteInfo']['stclr'] !== '' || $_SESSION['siteDetails']['siteInfo']['sitetitle'] !== '' || $_SESSION['siteDetails']['siteInfo']['sitemetadesc'] !== '' || $_SESSION['siteDetails']['siteInfo']['sitemetakey'] !== '' || $_SESSION['siteDetails']['siteInfo']['companyname'] !== '' || $_SESSION['siteDetails']['siteInfo']['captionname'] !== '') {
        @$doc->loadHTML(mb_convert_encoding($theData, 'HTML-ENTITIES', 'UTF-8'));

        // Add/Replace company name from customize site page
        if ($_SESSION['siteDetails']['siteInfo']['companyname'] != '') {
            applySiteCompany($_SESSION['siteDetails']['siteInfo']['companyname'], $_SESSION['siteDetails']['siteInfo']['compfont'], $_SESSION['siteDetails']['siteInfo']['fntclr'], $_SESSION['siteDetails']['siteInfo']['fontsize']);
        }

        // Add/Replace company name from customize site page
        if ($_SESSION['siteDetails']['siteInfo']['captionname'] != '') {
            applySiteCaption($_SESSION['siteDetails']['siteInfo']['captionname'], $_SESSION['siteDetails']['siteInfo']['captionfont'], $_SESSION['siteDetails']['siteInfo']['captfntclr'], $_SESSION['siteDetails']['siteInfo']['captionfontsize']);
        }

        // Add banner
        if ($createdSiteBanner && $createdSiteBannerName != '') {
            applySiteBanner($createdSiteBannerName, $createdSiteBannerLink);
        }

        if ($_SESSION['siteDetails']['siteInfo']['stclr'] !== '') {
            // Site Color
            applySiteColor($_SESSION['siteDetails']['siteInfo']['stclr']);
        }
        if ($_SESSION['siteDetails']['siteInfo']['sitetitle'] !== '') {
            // Site Page Title
            applySitePageTitle($_SESSION['siteDetails']['siteInfo']['sitetitle']);
        }
        if ($_SESSION['siteDetails']['siteInfo']['sitemetadesc'] !== '' || $_SESSION['siteDetails']['siteInfo']['sitemetakey'] !== '') {
            // Site Meta Desc/ Meta Keywords
            applySiteMetaData($_SESSION['siteDetails']['siteInfo']['sitemetakey'], $_SESSION['siteDetails']['siteInfo']['sitemetadesc']);
        }
        $theData = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $doc->saveHTML());
    }

    /*
     * ------------------ temp sort - need exact fix [image display path issues]---------------------
     * reset the path for the logo as it already comes with full url in index page
     */
    /*
    $theData = str_replace('src="' . BASE_URL . 'templates/' . $rowPanel['temp_id'] . '/', 'src="' . 'templates/' . $rowPanel['temp_id'] . '/', $theData);
    $theData = str_replace("src='" . BASE_URL . 'templates/' . $rowPanel['temp_id'] . '/', "src='" . 'templates/' . $rowPanel['temp_id'] . '/', $theData);
    
    $theData = str_replace('src="' . BASE_URL . 'uploads/', 'src="uploads/', $theData);
    $theData = str_replace("src='" . BASE_URL . 'uploads/', "src='uploads/", $theData);
    */
    
    $theData = str_replace('src="images/', 'src="' . BASE_URL . 'templates/' . $rowPanel['temp_id'] . '/images/', $theData);
    $theData = str_replace("src='images/", "src='" . BASE_URL . 'templates/' . $rowPanel['temp_id'] . '/images/', $theData);
    ?>
    <link rel="stylesheet" href="style/editor_styles.css" type="text/css">
    <link rel="stylesheet" type="text/css" href="style/dragdropstyles.css" />
    <link rel="stylesheet" href="style/common.css" />
    <script language="javascript" src="js/jquery.js"></script>
    <script>
        $(function () {

            // To disable the Form button actions
            $(".submitButton").live('click',(function() {
                return false;
            }));
            
            $("a").click(function() {
                var pagelink =$(this).attr('href');
                var pagelinkmode =$(this).attr('linkmode');
                if(pagelinkmode == 'external'){
                    if (pagelink && !pagelink.match(/^http([s]?):\/\/.*/)) {
                        pagelink = 'http://' + pagelink;
                    }
                    window.open(pagelink, '_blank');
                    return false;
                }
                
                if(pagelink != '' && pagelink != '#')
                    $("#sitepreviewcontent").load("editor_sitepreviewloader.php?page="+pagelink);
                return false;
            });
        });
    </script>

    <table width="100%"  border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td>
                <!-- a href="javascript:void(0);" style="float:right;" onclick="closePopup('300');">X</a> -->
                <div id="sitepreviewcontent"> <?php echo removeNotReplacableContent($theData); ?></div>   </td>
        </tr>
    </table>

    <?php
}
else
    echo "Error";
?>
