<?php

class photoalbum {

    var $pagename = 'index.php?module=photoalbum';
    var $int_glcode;
    var $chr_read;
    var $chr_star;
    var $chr_publish;
    var $int_displayorder;
    var $chr_delete = 'Y';
    var $dt_createdate;
    var $dt_modifydate;
    var $oldint_displayorder;
    var $numofrows;
    var $numofpages;
    var $orderby = 'int_glcode';
    var $ordertype = 'desc';
    var $searchby = '0';
    var $searchtxt;
    var $start = 1;
    var $pagesize = DEFAULT_PAGESIZE;
    var $pagenumber = '1';
    var $lastinsertid;
    var $urlwithpara = '';
    var $urlwithpoutsearch = '';
    var $urlwithoutsort = '';
    var $urlwithoutpaging = '';
    var $configObj;
    var $filterby = '0';
    var $urlwithoutfilter = '';
    var $display_limit_array = array(5, 10, 15, 30);
    var $varpostdata = array();
    var $thumb_width = TRADESHOW_THUMB_WIDTH;
    var $thumb_height = TRADESHOW_THUMB_HEIGHT;

    function photoalbum($configObj) {
        $this->sortvar = '<img alt="sorting" src="' . GLOBAL_ADMIN_IMAGES_PATH . 'arrow-up.png" style="vertical-align:middle;">';
        $this->configObj = $configObj;
    }

    function intitialize($view = '') {
        $this->searchby = (isset($_REQUEST['searchby'])) ? $_REQUEST['searchby'] : $this->searchby;
        $_REQUEST['searchtxt'] = ($_REQUEST['type'] == 'autosearch') ? $_REQUEST['term'] : $_REQUEST['searchtxt'];
        $this->searchbyVal = (isset($_REQUEST['searchbyVal'])) ? $_REQUEST['searchbyVal'] : $this->searchbyVal;
        $this->searchtxt = (isset($_REQUEST['searchtxt'])) ? $this->configObj->glLibraryObj->rem_special_chars($_REQUEST['searchtxt']) : '';
        $this->searchtxtjs = (isset($_REQUEST['searchtxt'])) ? $this->configObj->glLibraryObj->rem_special_chars_js($_REQUEST['searchtxt']) : '';

        $this->orderby = (isset($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : $this->orderby;
        $this->ordertype = (isset($_REQUEST['ordertype'])) ? $_REQUEST['ordertype'] : $this->ordertype;
        $this->filterby = (isset($_REQUEST['filterby'])) ? $_REQUEST['filterby'] : $this->filterby;

        if (isset($_REQUEST['sorting'])) {
            if ($this->ordertype == "asc") {   // This is for sort image
                $this->ordertype = "desc";
                $this->sortvar = "<img alt=\"sorting\" src=\"" . GLOBAL_ADMIN_IMAGES_PATH . "arrow-down.png\" style=\"vertical-align:middle;\">";
            } else if ($this->ordertype == "desc") {   // This is for sort image
                $this->ordertype = "asc";
                $this->sortvar = "<img alt=\"sorting\" src=\"" . GLOBAL_ADMIN_IMAGES_PATH . "arrow-up.png\" style=\"vertical-align:middle;\">";
            }
        }
        $this->pagesize = (isset($_REQUEST['pagesize'])) ? $_REQUEST['pagesize'] : $this->pagesize;
        $this->pagenumber = (isset($_REQUEST['pagenumber'])) ? $_REQUEST['pagenumber'] : $this->pagenumber;

        $this->start = ($this->pagenumber - 1 ) * $this->pagesize;
    }

    function getfacabookaccount() {
        $sql = "select * from " . DB_PREFIX . "facebook where chr_delete='N' and chr_publish='Y'";
        $rec = $this->configObj->glDbObj->query($sql);
        return $rec;
    }

    function getgoogle_account() {
        $sql = "select * from " . DB_PREFIX . "google_plus where chr_delete='N' and chr_publish='Y'";
        $rec = $this->configObj->glDbObj->query($sql);
        return $rec;
    }

    /*
     * Facebook and Twitter Start
     */

    function gettwitteraccount() {
        $sql = "select * from " . DB_PREFIX . "twitter where chr_delete='N' and chr_publish='Y'";
        $rec = $this->configObj->glDbObj->query($sql);
        return $rec;
    }

    function getphotogallerycustomdata() {
        $sql = "SELECT var_title,var_image FROM " . DB_PREFIX . "photoalbum WHERE chr_delete='N' AND int_glcode='" . $_REQUEST['eid'] . "'";
        $result = $this->configObj->glDbObj->get_sql_row($sql);
        return $result;
    }

    function genrateshareOption() {
//echo "dsfdsf";exit;
        $this->configObj->glTplObj->set('twitterresult', $this->gettwitteraccount());
        $this->configObj->glTplObj->set('result', $this->getfacabookaccount());
        $this->configObj->glTplObj->set('google_result', $this->getgoogle_account());
        $this->configObj->glTplObj->set('photogallerydata', $this->getphotogallerycustomdata());
        return $this->configObj->glTplObj->process('shareoption.tpl.php');
    }

    function getlogdetail($fb_tw_id, $articleid, $type = "F") {
        $sql = "select *,DATE_FORMAT(dt_createdate ,'" . DEFAULT_DATEFORMAT . "') as dt_createdate from " . DB_PREFIX . "sharelog where chr_type ='{$type}' and fk_facebook_twitter ={$fb_tw_id}  and fk_article={$articleid} and fk_module=91  order by dt_createdate desc limit 0,1";
        $rec = $this->configObj->glDbObj->query($sql);
        return $rec;
    }

    function get_Post_data($id) {
        $sql = "SELECT int_glcode,var_title,var_image,var_alias FROM " . DB_PREFIX . "photoalbum WHERE chr_delete='N' AND int_glcode='" . $id . "'";

        $result = $this->configObj->glDbObj->get_sql_row($sql);

        $imagename = $result['var_image'];
        $corePath = "upimages/photoalbum/images/";
        $imagepath = '../' . $corePath;
        $imagename = "thumb_" . $imagename;

        $image = $imagepath . $imagename;

        $imagelink = $corePath . $imagename;

        if ($imagename != "") {
            $image = (!file_exists($image)) ? "" : $image;
        } else {
            $image = "";
        }
        //echo $image;
        if (!empty($image)) {
            $image = SITE_PATH . $imagelink;
        }

        if (SITE_SEO == 'Y') {
            $photolink = SITE_PATH . $result["var_alias"];
        } else {
            $photolink = SITE_PATH . "photoalbum";
        }
        $paramArr['int_glcode'] = $id;
        $paramArr['data']['name'] = $this->varpostdata['var_title'];
        $paramArr["data"]["actions"] = array("name" => "Sent from Netclues PowerPanel", "link" => "http://www.netclues.ky");
        $paramArr['data']['link'] = $photolink;
        $paramArr['data']['picture'] = $image;
        if ($this->varpostdata['var_short_description'] != '') {
            $paramArr['data']['description'] = $this->varpostdata['var_short_description'];
        }

        return $paramArr;
    }

    function get_album_alias($id) {
        $sql = "SELECT int_glcode,var_title,var_image,var_alias FROM " . DB_PREFIX . "photoalbum WHERE chr_delete='N' AND int_glcode='" . $id . "'";

        $result = $this->configObj->glDbObj->get_sql_row($sql);
        return $result["var_alias"];
    }

    function shareonfacebook() {
        $status = 0;


        if (!empty($this->varpostdata['fb']) || !empty($this->varpostdata['tw']) || !empty($this->varpostdata['gl'])) {
            $eidArray = explode(",", $this->varpostdata['eid']);

            foreach ($eidArray as $eidvalue) {
                $param = $this->get_Post_data($eidvalue);
                if (!empty($this->varpostdata['fb'])) {

                    foreach ($this->varpostdata['fb'] as $value) {
                        // print_r($value);
                        $pageDetail = $this->getfbpagedetail($value);

                        $param["APP_ID"] = $pageDetail['var_application_id'];
                        $param["APP_SECRET"] = $pageDetail['var_seceret_key'];
                        $param["PAGE_ID"] = $pageDetail['var_page_id'];
                        $param["access_token"] = $pageDetail['var_oauth_token'];

                        if ($this->configObj->glLibraryObj->shareOnFacebook($param) == 1) {
                            $status = 1;
                            $this->addfbsharelog($pageDetail, $param, "F");
                        }
                    }
                }


                if (!empty($this->varpostdata['gl'])) {



                    foreach ($this->varpostdata['gl'] as $value) {
                        // print_r($value);
                        $pageDetail = $this->get_google_plus_pagedetail($value);


                        $param["APP_ID"] = $pageDetail['var_application_id'];
                        $param["APP_NAME"] = $pageDetail['var_pagename'];
                        $param["APP_SECRET"] = $pageDetail['var_seceret_key'];
                        $param["PAGE_ID"] = $pageDetail['var_page_id'];
                        $param["access_token"] = $pageDetail['var_oauth_token'];

//                        $this->configObj->glLibraryObj->shareOnGoogle_plus($param);
//                        $this->addfbsharelog($pageDetail, $param, "G");
//                         $status = 1;
                        echo $this->configObj->glLibraryObj->shareOnGoogle_plus($param);
                        exit;
                        if ($this->configObj->glLibraryObj->shareOnGoogle_plus($param) == 1) {
                            $status = 1;
                            $this->addfbsharelog($pageDetail, $param, "G");
                        }
                    }
                }


                if (!empty($this->varpostdata['tw'])) {
                    $eidArray = explode(",", $this->varpostdata['eid']);

                    $trid = $eidArray[0];
                    $albumalias = $this->get_album_alias($trid);
                    foreach ($this->varpostdata['tw'] as $value) {
                        $pageDetail = $this->gettwpagedetail($value);

                        $param['CONSUMER_KEY'] = $pageDetail['var_consumer_key'];
                        $param['CONSUMER_SECRET'] = $pageDetail['var_consumer_secret'];
                        $param['OUATH_TOKEN'] = $pageDetail['var_ouath_token'];
                        $param['OUATH_TOKEN_SECRET'] = $pageDetail['var_ouath_token_secret'];
                        $param['status'] = $param['name'];
                        $param['media'] = $param['picture'];
                        $titledata = strlen($param['data']['name']) > 50 ? substr($param['data']['name'], 0, 50) . "..." : $param['data']['name'];
                        $data = strlen($param['data']['description']) > 70 ? substr($param['data']['description'], 0, 70) . "..." : $param['data']['description'];
                        $param['data']['name'] = $titledata;
                        $param['data']['name'] .= "\n" . $data;


                        $param['data']['name'] .= "\n" . SITE_PATH . $albumalias;
//                        $param['data']['name'].=$param['media'];
                        if ($this->configObj->glLibraryObj->shareOnTwitter($param) == 1) {
                            $status = 1;
                            $this->addfbsharelog($pageDetail, $param, "T");
                        }
                    }
                }
            }
        }
        //print_r($_REQUEST);
        return $status;
    }

    function getfbpagedetail($id) {
        $sql = "select * from " . DB_PREFIX . "facebook where chr_delete='N' and chr_publish='Y' and int_glcode={$id}";
        $rec = $this->configObj->glDbObj->get_sql_row($sql);
        return $rec;
    }

    function get_google_plus_pagedetail($id) {
        $sql = "select * from " . DB_PREFIX . "google_plus where chr_delete='N' and chr_publish='Y' and int_glcode={$id}";
        $rec = $this->configObj->glDbObj->get_sql_row($sql);
        return $rec;
    }

    function gettwpagedetail($id) {
        $sql = "select * from " . DB_PREFIX . "twitter where chr_delete='N' and chr_publish='Y' and int_glcode={$id}";
        $rec = $this->configObj->glDbObj->get_sql_row($sql);
        return $rec;
    }

    function addfbsharelog($pageParam, $articleParam, $type) {
        $param = array(
            "fk_facebook_twitter" => $pageParam['int_glcode'],
            "fk_article" => $articleParam['int_glcode'],
            "chr_type" => $type,
            "dt_createdate" => "now()",
            "dt_modifydate" => "now()",
            "fk_module" => "91"
        );

        $this->configObj->glLibraryObj->insertIntoDB(DB_PREFIX . "sharelog", $param);
        $this->insertfacebooklogdata();
    }

    function insertfacebooklogdata() {
        $sql = "insert into " . DB_PREFIX . "facebooklog (fk_sharelogglcode,var_title,var_description,var_ipaddress,var_name) values ('" . mysql_insert_id() . "','" . $this->varpostdata['var_title'] . "','" . $this->varpostdata['var_short_description'] . "','" . $_SERVER['REMOTE_ADDR'] . "','" . ADMIN_NAME . "')";
        $this->configObj->glDbObj->query($sql);
    }

    /*
     * Facebook and Twitter End
     */

    function CountRows() {
        $this->intitialize($view);
        if (trim($this->searchtxt) != '') {
            $whereclause .= ($this->searchby == '0') ? " and var_title like '%$this->searchtxt%'" : " and $this->searchby like '%$this->searchtxt%'";
        }

        if ($this->filterby != '0' && $this->filterby != '') {
            $filterarray = explode('-', $this->filterby);
            $whereclause .= " and $filterarray[0] = '$filterarray[1]'";
        }

        $sqlCountPages = "select count(1) as total from " . DB_PREFIX . "photoalbum where chr_delete = 'N'  $whereclause ";
        $rs = $this->configObj->glDbObj->get_sql_row($sqlCountPages);
        $this->numofrows = $rs['total'];
        return $rs['total'];
    }

    function Generateurl() {
        $this->urlwithpara = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&numofrows=' . $this->numofrows . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs . '&pagenumber=' . $this->pagenumber . '&filterby=' . $this->filterby;
        $this->urlwithpoutsearch = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&filterby=' . $this->filterby;
        $this->urlwithoutsort = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&numofrows=' . $this->numofrows . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs . '&pagenumber=' . $this->pagenumber . '&ordertype=' . $this->ordertype . '&filterby=' . $this->filterby;
        $this->urlwithoutpaging = $this->pagename . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs . '&filterby=' . $this->filterby;
        $this->urlwithoutfilter = $this->pagename . '&' . 'pagesize=' . $this->pagesize . '&orderby=' . $this->orderby . '&ordertype=' . $this->ordertype . '&searchby=' . $this->searchby . '&searchtxt=' . $this->searchtxtjs;
        $this->configObj->AutoSearchUrl = $this->urlwithpara . "&type=autosearch&searchbyVal=" . $this->searchbyVal;
    }

    function org_generateParam($view = 'Photo albums', $actionurl = 'index.php?module=photoalbum&action=add', $searchArray = array("var_title" => "Username"), $table = 'DB_PREFIX.photoalbum', $position = 'top') {

        $filterPos = ($position == 'top') ? 'FT' : 'FB';
        return array('pageurl' => $this->pagename,
            'heading' => $view,
            'listImage' => 'add-new-user-icon.png',
            'tablename' => $table,
            'position' => $position,
            'actionImage' => 'add-new-button-blue.gif',
            'actionImageHover' => 'add-new-button-blue-hover.gif',
            'actionUrl' => $actionurl,
            'search' => array('searchArray' => $searchArray,
                'searchBy' => $this->searchby,
                'searchText' => $this->searchtxt,
                'searchUrl' => $this->urlwithpoutsearch
            ),
            'paging' => array('pagenumber' => $this->pagenumber,
                'noofpages' => $this->noofpages,
                'numofrows' => $this->numofrows,
                'pagingurl' => $this->urlwithpara
            ),
            'display' => array('displayurl' => $this->urlwithoutpaging,
                'pagesize' => $this->pagesize,
                'limitarray' => $this->display_limit_array,
            )
        );
    }

    function update_display_order($ids, $values, $oldvalues) {

        $tablename = DB_PREFIX . "photoalbum";
        for ($i = 0; $i < count($ids); $i++) {
            if ($values[$i] != $oldvalues[$i]) {
                $this->configObj->glDbObj->resetfields();
                $this->configObj->glDbObj->setQueryType('select');
                $this->configObj->glDbObj->setTable($tablename);
                $this->configObj->glDbObj->addColumn('count(1) as total');
                $this->configObj->glDbObj->setWhere("int_displayorder=" . $values[$i] . " and chr_delete = 'N' ");
                $rs = $this->configObj->glDbObj->get_sql_row($this->configObj->glDbObj->buildQuery());
                if ($rs['total'] > 0) {
                    if ($values[$i] > $oldvalues[$i]) {

                        $this->configObj->glDbObj->resetfields();
                        $this->configObj->glDbObj->setTable($tablename);
                        $this->configObj->glDbObj->setQueryType('update');
                        $this->configObj->glDbObj->addColumn('int_displayorder');
                        $this->configObj->glDbObj->UnsetQuotes();
                        $this->configObj->glDbObj->addValue('int_displayorder - 1');
                        $this->configObj->glDbObj->SetQuotes();
                        $this->configObj->glDbObj->setWhere("int_displayorder > " . $oldvalues[$i] . " and int_displayorder <= " . $values[$i] . " ");
                        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
                        // echo $this->configObj->glDbObj->buildQuery();
                    } else {
                        $this->configObj->glDbObj->resetfields();
                        $this->configObj->glDbObj->setTable($tablename);
                        $this->configObj->glDbObj->setQueryType('update');
                        $this->configObj->glDbObj->addColumn('int_displayorder');
                        $this->configObj->glDbObj->UnsetQuotes();
                        $this->configObj->glDbObj->addValue('int_displayorder + 1');
                        $this->configObj->glDbObj->SetQuotes();
                        $this->configObj->glDbObj->setWhere("int_displayorder >= " . $values[$i] . " and  int_displayorder < " . $oldvalues[$i] . "");
                        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
                    }
                }
                $this->configObj->glDbObj->resetfields();
                $this->configObj->glDbObj->setTable($tablename);
                $this->configObj->glDbObj->setQueryType('update');
                $this->configObj->glDbObj->addColumn('int_displayorder');
                $this->configObj->glDbObj->addValue($values[$i]);
                $this->configObj->glDbObj->setWhere("int_glcode=" . $ids[$i] . "");
                $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
            }
        }
    }

    function message($msg = '') {
        (string) $display_output = null;
        if ($msg != "") {
            $display_output .= "<div class=\"dverrorcustom\"><div class=\"confirmation-div\"><strong>$msg</strong></div></div>";
        }
        return $display_output;
    }

    function is_photoused() {
        $deleteids = $_REQUEST['dids'];
        $deletearray = explode(',', $deleteids);
        $totaldeletedrecords = count($deletearray);
        $is_assigned = 0;
        $delcount = 0;
        for ($i = 0; $i < $totaldeletedrecords; $i++) {
            $sql = "Update " . DB_PREFIX . "photoalbum set chr_delete='Y',dt_modifydate=NOW(),var_ipaddress='" . $_SERVER['REMOTE_ADDR'] . "',var_adminuser='" . ADMIN_NAME . " 'where int_glcode='$deletearray[$i]'";
            $this->configObj->glDbObj->query($sql);
            $delcount++;
            $this->configObj->glLibraryObj->insertinlogmanager(91, DB_PREFIX . 'photoalbum', 'var_title', $deletearray[$i], 'D');
        }
        $this->load_photogallery();
    }

    function loadCount() {
        $this->numofrows = $this->countFunction;
        $this->noofpages = intval($this->numofrows / $this->pagesize);
        $this->noofpages = (($this->numofrows % $this->pagesize) > 0) ? ($this->noofpages + 1) : ($this->noofpages);
        $this->configObj->glTplObj->set('numofrows', $this->numofrows);
        $this->Generateurl();
    }

    function load_photogallery() {
        if ($_REQUEST['task'] == 'orderupdate') {
            $updateids = $_REQUEST['uids'];
            $updatevalues = $_REQUEST['uvals'];
            $updateoldvalues = $_REQUEST['uoldvals'];
            $upidsarray = explode(',', $updateids);
            $upvalsarray = explode(',', $updatevalues);
            $upoldvalsarray = explode(',', $updateoldvalues);
            $this->update_display_order($upidsarray, $upvalsarray, $upoldvalsarray);
        }
        $this->pagename = 'index.php?module=photoalbum';

        $this->configObj->glTplObj->set('numofrows', $this->numofrows);
        $this->loadCount_photo('CountPhotogalleryRows');
        $result = $this->selectall_photogallery();
        $this->configObj->glTplObj->set('result', $result);
        $searchArray = array("var_title" => "Title");
        $view = 'Manage Photo Albums';
        $actionurl = 'index.php?module=photoalbum&action=add';
        $table = DB_PREFIX . 'photoalbum';
        $parmas = $this->org_generateParam($view, $actionurl, $searchArray, $table);

        $this->configObj->glTplObj->set('headerpanel', $this->configObj->glLibraryObj->generateHeaderPanel($parmas));
        $this->configObj->glTplObj->set('pagingTop', $this->configObj->glLibraryObj->generatePagingPannel($parmas));
        $this->configObj->glTplObj->set('pagingBottom', $this->configObj->glLibraryObj->generatePagingPannel($this->org_generateParam($view, $actionurl, $searchArray, $table, 'bottom')));

        //For Note
        $notemessagebox = $this->configObj->glLibraryObj->notemessage("Note : ", "Adding albums are incremental, once you add a new album it will display as first album and previous albums will move down in the order.");
        $this->configObj->glTplObj->set('notemessagebox', $notemessagebox);

        // Set the sorting image
        $tmpsetsortvar = 'setsortimg' . $this->orderby;
        $$finalsortvar = $tmpsetsortvar;
        $this->configObj->glTplObj->set($$finalsortvar, $this->sortvar);

        // End of Set the sorting image
        if ($_REQUEST['msg'] == 'add') {
            $messagebox = $this->configObj->glLibraryObj->message("The record has been successfully saved.");
            $this->configObj->glTplObj->set('messagebox', $messagebox);
        }
        if ($this->configObj->isAjaxSet) {
            echo $this->configObj->glTplObj->process('photoalbum.tpl.php');
            exit;
        } else {
            $this->configObj->adminContentPanel = $this->configObj->glTplObj->process('photoalbum.tpl.php');
        }
    }

    function selectall_photogallery() {
        $this->configObj->glDbObj->resetfields(); // Reset the object
        $this->configObj->glDbObj->setQueryType('select');    // Set the Table
        $tablename = DB_PREFIX . "photoalbum";
        $this->configObj->glDbObj->setTable($tablename);
        $this->configObj->glDbObj->addColumn('*');

        $whereclause = "chr_delete = 'N'";
        if ($this->filterby != '0' && $this->filterby != '') {
            $filterarray = explode('-', $this->filterby);
            $whereclause .= " and $filterarray[0] = '$filterarray[1]'";
        }
        if ($this->accessories != '0' && $this->accessories != '') {
            $whereclause .= " and accessory_type='" . $this->accessories . "'";
        }
        if (trim($this->searchtxt) != '') {
            $whereclause .= ($this->searchby == '0') ? " and (var_title like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%') " : " and $this->searchby like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%'";
        }
        $this->configObj->glDbObj->setWhere($whereclause);
        $this->configObj->glDbObj->setOrderBy($this->orderby . ' ' . $this->ordertype);
        $this->configObj->glDbObj->setLimit($this->start . ', ' . $this->pagesize);

        if ($_REQUEST['type'] == 'autosearch') {
            $orderby = (isset($_REQUEST['orderby'])) ? 'order by ' . $this->orderby . ' ' . $this->ordertype : 'order by int_displayorder';

            $searchbyVal = (!empty($this->searchbyVal)) ? " chr_delete = 'N' and {$this->configObj->glDbObj->addSlashes($this->searchbyVal)} like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%' " : "$whereclause";

            if ($this->searchbyVal == '0') {
                $this->searchbyVal = "var_title";
            }
            if ($this->searchbyVal == 'var_title') {
                $this->searchbyVal = "var_title";
            }

            if ($this->filterby != '0' && $this->filterby != '') {
                $filterarray = explode('-', $this->filterby);
                $whereclauseauto = " and $filterarray[0] = '$filterarray[1]'";
            }

            $searchbyVal1 = "{$this->searchbyVal} like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%' and chr_delete = 'N'";
            $autoSearchQry = "select int_glcode ," . $this->searchbyVal . " as AutoVal FROM " . $tablename . " where  $searchbyVal1 $whereclauseauto group by " . $this->searchbyVal . " $orderby";
            $this->configObj->glLibraryObj->GetAutoSearch($autoSearchQry);
        }
        $rs = $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        //echo $this->configObj->glDbObj->buildQuery(); exit;
        return $rs;
    }

    function loadCount_photo($function) {
        $this->intitialize();
        $this->{$function}();
        $this->noofpages = intval($this->numofrows / $this->pagesize);
        $this->noofpages = (($this->numofrows % $this->pagesize) > 0) ? ($this->noofpages + 1) : ($this->noofpages);
        $this->configObj->glTplObj->set('numofrows', $this->numofrows);
        $this->Generateurl();
    }

    function CountPhotogalleryRows() {
        $this->intitialize();

        if (trim($this->searchtxt) != '') {
            $whereclause .= ($this->searchby == '0') ? " and var_title like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%'" : " and $this->searchby like '%" . $this->configObj->glDbObj->addSlashes($this->searchtxt) . "%'";
        }
        if ($this->filterby != '0' && $this->filterby != '') {
            $filterarray = explode('-', $this->filterby);
            $whereclause .= " and $filterarray[0] = '$filterarray[1]'";
        }
        $sqlCountPages = "select count(1) as total from " . DB_PREFIX . "photoalbum where chr_delete = 'N' $whereclause ";
        $rs = $this->configObj->glDbObj->get_sql_row($sqlCountPages);
        $this->numofrows = $rs['total'];
        return $rs['total'];
    }

    function updatedisplay_order($tablename, $intdisplay) {
        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('update');
        $this->configObj->glDbObj->setTable(DB_PREFIX . $tablename);
        $this->configObj->glDbObj->addColumn('int_displayorder');
        $this->configObj->glDbObj->UnsetQuotes();
        $this->configObj->glDbObj->addValue('int_displayorder + 1');
        $this->configObj->glDbObj->SetQuotes();
        $this->configObj->glDbObj->setWhere("int_displayorder >=" . $intdisplay . " and chr_delete = 'N' ");
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        return true;
    }

    function insert_photo() {

        if ($this->varpostdata['int_displayorder'] != '' && $this->varpostdata['int_displayorder'] != '0') {
            $intdiplayorder = $this->varpostdata['int_displayorder'];
        } else {
            $intdiplayorder = 1;
        }
        $this->updatedisplay_order('photoalbum', $intdiplayorder);
        $sess = time();

        if ($_FILES['var_image']['name'] != '') {

            //for removing space in name
            $file_extension = $this->configObj->glLibraryObj->file_extension($_FILES['var_image']['name']);
            $photo = basename($_FILES['var_image']['name']);
            $photofile = str_replace(' ', '-', $photo);
            $phototitle = explode('.', $photofile);
            $var_title = $phototitle[0];
            $_FILES['var_image']['name'] = $photofile;

            $image_width = PHOTO_ALBUM_WIDTH;
            $image_height = PHOTO_ALBUM_HEIGHT;
            $var_thumb = $this->upload_image('var_image', $image_width, $image_height, 'thumb_', $sess, $image_width, $image_height, 'thumb_');
            $this->imagename = $var_thumb;
        }
        if ($_REQUEST['var_title'] != '') {
            $pagename = $_REQUEST['var_title'];
        } else {
            $pagename = $var_title;
        }

        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('insert');
        $this->configObj->glDbObj->setTable(DB_PREFIX . 'photoalbum');

        // Set the Columns
        $this->configObj->glDbObj->addColumn('var_title');
        $this->configObj->glDbObj->addColumn('var_alias');
        $this->configObj->glDbObj->addColumn('var_image');
        $this->configObj->glDbObj->addColumn('chr_delete');
        $this->configObj->glDbObj->addColumn('dt_createdate');
        $this->configObj->glDbObj->addColumn('dt_modifydate');
        $this->configObj->glDbObj->addColumn('var_metatitle');
        $this->configObj->glDbObj->addColumn('var_metakeyword');
        $this->configObj->glDbObj->addColumn('var_metadescription');

        // Set the Values
        $this->configObj->glDbObj->addValue(htmlspecialchars($pagename));
        $this->configObj->glDbObj->addValue($_REQUEST['var_alias']);
        $this->configObj->glDbObj->addValue($this->imagename);
        $this->configObj->glDbObj->addValue('N');
        $this->configObj->glDbObj->addValue('NOW()');
        $this->configObj->glDbObj->addValue('NOW()');
        $this->configObj->glDbObj->addValue($this->varpostdata['var_metatitle']);
        $this->configObj->glDbObj->addValue($this->varpostdata['var_metakeyword']);
        $this->configObj->glDbObj->addValue($this->varpostdata['var_metadescription']);
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());

        $this->lastinsertid = mysql_insert_id();
        $this->configObj->glLibraryObj->insertinlogmanager(91, DB_PREFIX . 'photoalbum', 'var_title', $this->lastinsertid, 'I');
        return true;
    }

    function update_photos() {
        $sess = time();
        if ($_FILES['var_image']['name'] != '') {

            //for removing space in name
            $file_extension = $this->configObj->glLibraryObj->file_extension($_FILES['var_image']['name']);
            $pdf = basename($_FILES['var_image']['name']);
            $pdffile = str_replace(' ', '-', $pdf);

            $_FILES['var_image']['name'] = $pdffile;
            $this->imagename = $_FILES['var_image']['name'];
            $image_width = PHOTO_ALBUM_WIDTH;
            $image_height = PHOTO_ALBUM_HEIGHT;

            $var_thumb = $this->upload_image('var_image', $image_width, $image_height, 'thumb_', $sess, $image_width, $image_height, 'thumb_');
            $this->imagename = $var_thumb;
            $uploaddir = '../upimages/photoalbum/images/';
            $uploadfile = $uploaddir . $this->varpostdata['hidvar_photo1'];
            $uploadthumb = $uploaddir . "thumb_" . $this->varpostdata['hidvar_photo1'];
            $uploadthumb1 = $uploaddir . "thumb_small" . $this->varpostdata['hidvar_photo1'];

            if (file_exists($uploadfile)) {
                unlink($uploadfile);
            }
            if (file_exists($uploadthumb)) {
                unlink($uploadthumb);
            }
        } else {

            $this->imagename = $this->varpostdata['hidvar_photo'];
        }

        $this->configObj->glDbObj->resetfields();
        $this->configObj->glDbObj->setQueryType('update');
        $this->configObj->glDbObj->setTable(DB_PREFIX . 'photoalbum');
        // Set the Columns
        $this->configObj->glDbObj->addColumn('var_title');
        $this->configObj->glDbObj->addColumn('var_alias');
        $this->configObj->glDbObj->addColumn('var_image');
        $this->configObj->glDbObj->addColumn('dt_modifydate');
        $this->configObj->glDbObj->addColumn('var_metatitle');
        $this->configObj->glDbObj->addColumn('var_metakeyword');
        $this->configObj->glDbObj->addColumn('var_metadescription');

        $this->configObj->glDbObj->addValue(htmlspecialchars($this->varpostdata['var_title']));
        $this->configObj->glDbObj->addValue($this->varpostdata['var_alias']);
        $this->configObj->glDbObj->addValue($this->imagename);
        $this->configObj->glDbObj->addValue('NOW()');
        $this->configObj->glDbObj->addValue($this->varpostdata['var_metatitle']);
        $this->configObj->glDbObj->addValue($this->varpostdata['var_metakeyword']);
        $this->configObj->glDbObj->addValue($this->varpostdata['var_metadescription']);
        $this->configObj->glDbObj->setWhere('int_glcode=' . $this->varpostdata['eid']);
        $this->configObj->glDbObj->query($this->configObj->glDbObj->buildQuery());
        $this->lastinsertid = $this->varpostdata['eid'];

        $this->configObj->glLibraryObj->insertinlogmanager(91, DB_PREFIX . 'photoalbum', 'var_title', $this->varpostdata['eid'], 'U');
        return true;
    }

    function select_photo($id) {

        $this->configObj->glDbObj->resetfields(); // Reset the object
        $this->configObj->glDbObj->setQueryType('select');    // Set the Table
        $this->configObj->glDbObj->setTable(DB_PREFIX . 'photoalbum');
        $this->configObj->glDbObj->addColumn('*');
        $this->configObj->glDbObj->setWhere('int_glcode =' . $id);
        $row = $this->configObj->glDbObj->get_sql_row($this->configObj->glDbObj->buildQuery());
        return $row;
    }

    function upload_image($filefield, $thumb_width, $thumb_height, $prefix, $sess, $large_width, $large_height, $prefix2 = '') {
        //echo $filefield;exit;///////////////// echo 'tttttttt'.$filefield;
        $file_photo = basename($_FILES[$filefield]['name']);
        $imagename = $sess . $file_photo;
        $uploaddir = '../upimages/photoalbum/images/';
        $file_photo = $sess . basename($_FILES[$filefield]['name']);
        $file = $uploaddir . $file_photo;
        $tmp = $_FILES[$filefield]['tmp_name'];
        $uploadedfile = $_FILES[$filefield]['tmp_name'];
        // Create an Image from it so we can do the resize
        $image_info = getimagesize($uploadedfile);

        switch ($image_info['mime']) {
            case 'image/gif':
                $img_create = 'ImageCreateFromGIF';
                break;
            case 'image/jpeg':
                $img_create = 'ImageCreateFromJPEG';
                break;
            case 'image/png':
                $img_create = 'ImageCreateFromPNG';
                break;
            case 'image/bmp':
                $img_create = 'ImageCreateFromBMP';
                break;
        }
        $photoexe = explode('.', $imagename);
        $photoexename = $photoexe[count($photoexe) - 1];
        if ($photoexename == 'bmp') {
            $src = $this->configObj->glLibraryObj->imagecreatefrombmp($uploadedfile);
        } else {
            $src = @$img_create($uploadedfile);
        }
        // Capture the original size of the uploaded image
        list($width, $height) = getimagesize($uploadedfile);
        $newwidth = $width;
        $newheight = $height;

        $tmp = imagecreatetruecolor($newwidth, $newheight);
        $background_color = imagecolorallocate($tmp, 255, 255, 255);
        imagefill($tmp, 0, 0, $background_color);

        // this line actually does the image resizing, copying from the original // image into the $tmp image
        imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        // now write the resized image to disk.
        imagejpeg($tmp, $file, 90);
        imagedestroy($src);
        imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request  // has completed.

        $source1 = $uploaddir . $file_photo;

        //$sess = time();
        $thumbfilename = $prefix . $sess . $file_photo;
        $target1 = $uploaddir . $prefix . $file_photo;
        $target2 = $uploaddir . $prefix2 . $file_photo;
        if ($large_width > 0) {
            $returnthumbmsg1 = $this->configObj->glLibraryObj->generate_thumb($source1, $thumb_width, false, false, $target1, false, null, $thumb_width, $thumb_height);
        }
        if ($large_width > 0) {
            $returnthumbmsg2 = $this->configObj->glLibraryObj->generate_thumb($source1, $thumb_width, false, false, $target2, false, null, $large_width, $large_height);
        }
        if ($returnthumbmsg1 == 'INVALID' || $returnthumbmsg2 == 'INVALID') {
            $this->chr_validthumb = 'N';
            $this->chr_validthumbdetail = 'N';
        } else {
            $this->chr_validthumb = 'Y';
            $this->chr_validthumbdetail = 'Y';
        }
        return $imagename;
    }

    function countphoto($id) {
        $sql = 'select count(1) as total from ' . DB_PREFIX . 'photogallery where chr_delete="N" and fk_album="' . $id . '"';
        $rs = $this->configObj->glDbObj->get_sql_row($sql);
        return $rs['total'];
    }

}

?>