<?php
/*
 * @package Joomla 3.0
 * @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 *
 * @component XMovie Component
 * @copyright Copyright (C) Dana Harris optikool.com
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 */
defined('_JEXEC') or die('Restricted access');

class MovieHelper
{

    protected static $lookup;

    /**
     * Gets a list of the actions that can be performed.
     * @param    int        The category ID.
     * @return    JObject
     */
    public static function getActions($categoryId = 0, $movieId = 0)
    {
        $user = JFactory::getUser();
        $result = new JObject;

        if (empty($categoryId)) {
            $assetName = 'com_xmovie';
        } else {
            $assetName = 'com_xmovie.category.' . (int)$categoryId;
        }

        $actions = array('core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.own', 'core.edit.state', 'core.delete');

        foreach ($actions as $action) {
            $result -> set($action, $user -> authorise($action, $assetName));
        }

        return $result;
    }

    public static function getTopId($id)
    {
        $db = JFactory::getDbo();
        $query = $db -> getQuery(true);

        $query -> select('id');
        $query -> from('#__menu');
        $query -> where("`link` LIKE '%option=com_xmovie%'");
        $query -> where("`link` LIKE '%view=category%'");
        $query -> where("`link` LIKE '%id={$id}%'");

        $db -> setQuery($query);
        $result = $db -> loadResult();

        return $result;
    }

    /**
     * Get the top level parent cid from list of ids
     * @param view current view. main or category
     * @param array $catid Id of the category if any
     * @return object list
     */
    public static function getTopLevel($view = "main", $id = 0, $menutype = null)
    {
        $db = JFactory::getDbo();
        $query = $db -> getQuery(true);

        $query -> select('id, alias, title, link');
        $query -> from('#__menu');

        if ($menutype != null) {
            $menutype = " `menutype` = '{$menutype}' AND";
        } else {
            $menutype = "";
        }

        if ($view == "main") {
            $query -> where("lft > (SELECT lft FROM #__menu WHERE{$menutype} `link` LIKE '%view=main%' AND `link` LIKE '%option=com_xmovie%' AND `client_id` = '0' AND `published` = '1')");
            $query -> where("rgt < (SELECT rgt FROM #__menu WHERE{$menutype} `link` LIKE '%view=main%' AND `link` LIKE '%option=com_xmovie%' AND `client_id` = '0' AND `published` = '1')");

        } else {
            $query -> where("lft > (SELECT lft FROM #__menu WHERE{$menutype} `link` LIKE '%id=" . $id . "%' AND `link` LIKE '%view=category%' AND `link` LIKE '%option=com_xmovie%' AND `client_id` = '0' AND `published` = '1')");
            $query -> where("rgt < (SELECT rgt FROM #__menu WHERE{$menutype} `link` LIKE '%id=" . $id . "%' AND `link` LIKE '%view=category%' AND `link` LIKE '%option=com_xmovie%' AND `client_id` = '0' AND `published` = '1')");
        }

        $query -> where("`link` LIKE '%option=com_xmovie%'");
        $query -> where("`link` LIKE '%view=category%'");
        $query -> where("`client_id` = '0'");
        $query -> where("`published` = '1'");
        $query -> order("(rgt-lft) ASC");
        $db -> setQuery($query);
        $categories = $db -> loadObjectList('id');
        $result = array();

        foreach ($categories as $category) {
            parse_str($category -> link, $queryString);

            $resultId = $queryString['id'];
            $result[$resultId] = new stdClass();
            $result[$resultId] -> id = $resultId;
            $result[$resultId] -> menuid = $category -> id;
            $result[$resultId] -> alias = $category -> alias;
            $result[$resultId] -> title = $category -> title;
            $result[$resultId] -> link = $category -> link;
        }

        return $result;
    }

    /**
     * Get a list of items ids currently in the menu table.
     * @return ObjectList
     */
    public static function getItemIds()
    {
        $itemids = array();

        $db = JFactory::getDBO();
        $query = $db -> getQuery(true);

        $query -> select('id, link, alias, lft, rgt');
        $query -> from('#__menu');
        $query -> where("client_id = '0'");
        $query -> where("lft >= ANY (SELECT lft FROM `#__menu` WHERE `link` LIKE '%view=main%' AND `link` LIKE '%option=com_xmovie%' AND `client_id` = '0')");
        $query -> where("rgt <= ANY (SELECT rgt FROM `#__menu` WHERE `link` LIKE '%view=main%' AND `link` LIKE '%option=com_xmovie%' AND `client_id` = '0')");
        $query -> where("published = 1");

        $db -> setQuery($query);
        $mList = $db -> loadObjectList();

        foreach ($mList as $key => $value) {
            $uLink = parse_url($value -> link);
            parse_str($uLink['query'], $uQuery);

            if (isset($uQuery['id'])) {
                $tmpId = $uQuery['id'];
                $itemids[$tmpId]['id'] = $tmpId;
                $itemids[$tmpId]['itemId'] = $value -> id;
                $itemids[$tmpId]['link'] = $value -> link;
                $itemids[$tmpId]['alias'] = $value -> alias;
                $itemids[$tmpId]['lft'] = $value -> lft;
                $itemids[$tmpId]['rgt'] = $value -> rgt;
            } else {
                $itemids[0]['id'] = '0';
                $itemids[0]['itemId'] = $value -> id;
                $itemids[0]['link'] = $value -> link;
                $itemids[0]['alias'] = $value -> alias;
                $itemids[0]['lft'] = $value -> lft;
                $itemids[0]['rgt'] = $value -> rgt;
            }
        }

        return $itemids;
    }

    /**
     * Function to get the users access level
     *
     * @return type The list of access levels
     */
    public static function getAccessLevel()
    {
        $user = &JFactory::getUser();
        $type = '';
        switch ($user->usertype) {
            case '' :
                $type = " AND access='0'";
                break;
            case 'Registered' :
                $type = " AND (access='0' OR access='1')";
                break;
            default :
                $type = " AND (access='0' OR access='1' OR access='2')";
                break;
        }
        return $type;
    }

    /**
     * Function to get both movie and category access levels.
     *
     * @return type The list of access levels
     */
    public static function getAccessLevelCC()
    {
        $user = &JFactory::getUser();
        $type = '';
        switch ($user->usertype) {
            case '' :
                $typeCat = " AND #__xmovie_categories.access='0'";
                $typeCol = " AND #__xmovie_movies.access='0'";
                break;
            case 'Registered' :
                $typeCat = " AND (#__xmovie_categories.access='0' OR #__xmovie_categories.access='1')";
                $typeCol = " AND (#__xmovie_movies.access='0' OR #__xmovie_movies.access='1')";
                break;
            default :
                $typeCat = " AND (#__xmovie_categories.access='0' OR #__xmovie_categories.access='1' OR #__xmovie_categories.access='2')";
                $typeCol = " AND (#__xmovie_movies.access='0' OR #__xmovie_movies.access='1' OR #__xmovie_movies.access='2')";
                break;
        }

        $type = $typeCol . $typeCat;
        return $type;
    }

    /**
     * Function to check access level on categories
     *
     */
    public static function checkAccessLevel($cat)
    {
        $option = JRequest::getCmd('option');
        $user = &JFactory::getUser();
        $type = '';

        $query = "SELECT access FROM #__xmovie_categories WHERE published = '1' AND id ='{$cat}' LIMIT 1";
        $row = $this -> _getList($query);

        switch ($user->usertype) {
            case '' :
                $type = array('0');
                break;
            case 'Registered' :
                $type = array('0', '1');
                break;
            default :
                $type = array('0', '1', '2');
                break;
        }

        if (!in_array($row[0] -> access, $type)) {
            $itemid = MovieHelper::getXMovieItemId();
            $slug = $cat . ":" . MovieHelper::getCategorySlug();
            $link = "index.php?option=com_xmovie&view=category&id={$slug}&Itemid={$itemid->id}";
            $redirectUrl = base64_encode($link);
            $redirectUrl = '&return=' . $redirectUrl;
            $joomlaLoginUrl = 'index.php?option=com_user&view=login';
            $finalUrl = $joomlaLoginUrl . $redirectUrl;

            header('Location: ' . JRoute::_($finalUrl));
        }
    }

    /**
     * Function to to check Movie access level
     */
    public static function checkMovieAccess($id)
    {
        $option = JRequest::getCmd('option');

        $user = &JFactory::getUser();
        $type = '';

        $query = "SELECT access FROM #__xmovie_movies WHERE published = '1' AND id ='{$id}' LIMIT 1";
        $row = $this -> _getList($query);

        switch ($user->usertype) {
            case '' :
                $type = array('0');
                break;
            case 'Registered' :
                $type = array('0', '1');
                break;
            default :
                $type = array('0', '1', '2');
                break;
        }

        if (!in_array($row[0] -> access, $type)) {
            $itemid = MovieHelper::getXMovieItemId();
            $cat = MovieHelper::getCategory($id);
            $slugcat = $cat -> cid . ":" . MovieHelper::getCategorySlug();
            $slug = $id . ":" . MovieHelper::getMovieSlug();
            $link = "index.php?option=com_xmovie&view=single&catid={$slugcat}&id={$slug}&Itemid={$itemid->id}";
            $redirectUrl = base64_encode($link);
            $redirectUrl = '&return=' . $redirectUrl;
            $joomlaLoginUrl = 'index.php?option=com_user&view=login';
            $finalUrl = $joomlaLoginUrl . $redirectUrl;

            header('Location: ' . JRoute::_($finalUrl));
        }
    }

    /**
     * @param    int    The route of the weblink
     */
    public static function getXMovieRoute($id, $catid)
    {
        $itemIds = MovieHelper::getItemIds();
        list($cid, $cidslug) = explode(":", $catid);
        $link = "index.php?option=com_xmovie&view=single&id={$id}&catid={$catid}&Itemid=" . $itemIds[$cid]['itemId'];
        return $link;
    }

    protected static function _findItem($needles = null)
    {
        $app = JFactory::getApplication();
        $menus = $app -> getMenu('site');

        // Prepare the reverse lookup array.
        if (self::$lookup === null) {
            self::$lookup = array();

            $component = JComponentHelper::getComponent('com_xmovie');
            $items = $menus -> getItems('component_id', $component -> id);

            if ($items) {
                foreach ($items as $item) {
                    if (isset($item -> query) && isset($item -> query['view'])) {
                        $view = $item -> query['view'];

                        if (!isset(self::$lookup[$view])) {
                            self::$lookup[$view] = array();
                        }

                        if (isset($item -> query['id'])) {
                            self::$lookup[$view][$item -> query['id']] = $item -> id;
                        }
                    }
                }
            }
        }

        if ($needles) {
            foreach ($needles as $view => $ids) {
                if (isset(self::$lookup[$view])) {
                    foreach ($ids as $id) {
                        if (isset(self::$lookup[$view][(int)$id])) {
                            return self::$lookup[$view][(int)$id];
                        }
                    }
                }
            }
        } else {
            $active = $menus -> getActive();
            if ($active) {
                return $active -> id;
            }
        }

        return null;
    }

    /**
     * Function to format links for SEO
     *
     * @return link The formatted link
     */
    public static function getRoute($link)
    {
        $link = JRoute::_($link);
        return $link;
    }

    /**
     * Function to return the visitors browser type.
     *
     * @return browser Array with the browser version and name
     */
    public static function getBrowserType()
    {
        $useragent = $_SERVER['HTTP_USER_AGENT'];
        $browser = array();
        if (preg_match('|MSIE ([0-9].[0-9]{1,2})|', $useragent, $matched)) {
            $browser['browser_version'] = $matched[1];
            $browser['browser'] = 'IE';
        } elseif (preg_match('|Opera ([0-9].[0-9]{1,2})|', $useragent, $matched)) {
            $browser['browser_version'] = $matched[1];
            $browser['browser'] = 'Opera';
        } elseif (preg_match('|Firefox/([0-9\.]+)|', $useragent, $matched)) {
            $browser['browser_version'] = $matched[1];
            $browser['browser'] = 'Firefox';
        } elseif (preg_match('|Safari/([0-9\.]+)|', $useragent, $matched)) {
            $browser['browser_version'] = $matched[1];
            $browser['browser'] = 'Safari';
        } else {
            // browser not recognized!
            $browser['browser_version'] = 0;
            $browser['browser'] = 'other';
        }

        return $browser;
    }

    public static function getVideoTemplate($type = '16') {
        $movieTemplate = 'tpl_mp4';

        switch ($type) {
            case '1' :
                // You Tube
            	$movieTemplate = 'tpl_youtube';
                break;
            case '2' :
                // Daily Motion
                $movieTemplate = 'tpl_dailymotion';
                break;
            case '3' :
                // Meta Cafe
                $movieTemplate = 'tpl_metacafe';
                break;
            case '6' :
                // Veoh
                $movieTemplate = 'tpl_veoh';
                break;
            case '7' :
                // Vimeo
                $movieTemplate = 'tpl_vimeo';
                break;          
                // DIVX Local
                $movieTemplate = 'tpl_divx';
                break;
            case '10' :
                // AVI Local
                $movieTemplate = 'tpl_avi';
                break;
            case '11' :
                // MOV Local
                $movieTemplate = 'tpl_mov';
                break;
            case '12' :
                // SWF Local
                $movieTemplate = 'tpl_swf';
                break;
            case '13' :
                // FLV Local
                $movieTemplate = 'tpl_flv';
                break;
            case '14' :
                // F4V Local
                $movieTemplate = 'tpl_f4v';
                break;
            case '15' :
                // WMV Local
                $movieTemplate = 'tpl_wmv';
                break;
            case '16' :
            case '9' :
                // MP4 Local
                $movieTemplate = 'tpl_mp4';
                break;
            case '17' :
            case '18' :
            case '32' :
                // RM Local
                // RAM 
                // RMVB
                $movieTemplate = 'tpl_rm';
                break;
            case '30' :
                // m3u8 Local
                $movieTemplate = 'tpl_m3u8';
                break;
            case '29' :
                $movieTemplate = 'tpl_raw';
            default :
                break;
        }

        return $movieTemplate;
    }

    /**
     * Function to get the embed code for the video.
     *
     * @return
     */
    public static function getEmbedCode(&$movie, $width = 0, $height = 0, $percent = '')
    {
        $cfgParams = JComponentHelper::getParams('com_xmovie');
        $image_path = JComponentHelper::getParams('com_media') -> get('image_path', 'images');
        $single_max_width = $cfgParams -> get('single_max_width');
        $single_max_height = $cfgParams -> get('single_max_height');
        $single_base_font = $cfgParams -> get('base_font_size');
        $flow_player_swf = JURI::root() . 'components/com_xmovie/js/fp/flowplayer.swf';

        if (!defined('COM_XMOVIE_BASEURL')) {
            $movie_Path = $cfgParams -> get('movie_path');
            $baseurl = JURI::root() . $cfgParams -> get('movie_path');
        } else {
            $baseurl = COM_XMOVIE_BASEURL;
        }

        $iPod = stripos($_SERVER['HTTP_USER_AGENT'], "iPod");
        $iPhone = stripos($_SERVER['HTTP_USER_AGENT'], "iPhone");
        $iPad = stripos($_SERVER['HTTP_USER_AGENT'], "iPad");
        $android = stripos($_SERVER['HTTP_USER_AGENT'], "Android");
        $controls = '';

        if ($cfgParams -> get('enable_movie_background')) {
            $url = parse_url($movie -> thumb);
            $thumbPath = JURI::root() . $image_path . DS . $cfgParams -> get('movie_thumb_path');

            if (!array_key_exists('host', $url)) {
                $thumbPath = $thumbPath . DS . $movie -> thumb;
            } else {
                $thumbPath = $movie -> thumb;
            }
        } else {
            $thumbPath = '';
        }

        if ($cfgParams -> get('cview_autoplay')) {
            $autoplay = "true";
        } else {
            $autoplay = "false";
        }
        $autoplaystring = "&autoplay={$autoplay}";
        $embed = '';

        if ($width != 0 && $height != 0) {
            $single_max_width = $width;
            $single_max_height = $height;
        }

        if ($percent === '') {
            $percent = $cfgParams -> get('pixel_percent');
        }

        $format = JRequest::getString('format', '');
        if ($format != '' && $format == 'raw') {
            $single_max_width = JRequest::getInt('w', '');
            $single_max_height = JRequest::getInt('h', '');
            $percent = JRequest::getString('pp', '');
        }
        $size = MovieHelper::calDimenions($movie -> width, $movie -> height, $single_max_width, $single_max_height, $percent);
        $px = '';
		
		$analytics = '';
		//$youtubeparams = '?enablejsapi=1&origin=' . JURI::base();
		$accountId = $cfgParams->get('ganalytics_key');
        $size = MovieHelper::calDimenions($movie -> width, $movie -> height, $single_max_width, $single_max_height, $percent);
		
		if($cfgParams->get('enable_ganalytics') && $accountId !== '') {
			$analytics = $accountId;	
		} else {
			$youtubeparams = '';
		}

        switch ($percent) {
            case 'pixel' :
                $px = 'px';
                break;
            case 'em' :
                $px = 'em';
                $size['width'] = MovieHelper::getPixelToEm($size['width'], $single_base_font);
                $size['height'] = MovieHelper::getPixelToEm($size['height'], $single_base_font);
                break;
            default :
                $px = '';
        }

        switch ($movie->type) {
            case '1' :
                // You Tube
            	$document = JFactory::getDocument();
                $name = 'xmovie-youtube';
                $attrs = "width='{$size['width']}{$px}' height='{$size['height']}{$px}' frameborder='0' allowfullscreen";
                $embed = '<div id="'.$name.'"></div>'; // JHtml::iframe($movie -> link . $youtubeparams, $name, $attrs);
                $embed .= MovieHelper::getYoutubePlayerCode($movie, $size['width'], $size['height'], 'xmovie-youtube');
                //$document->addScript(JURI::base().'/components/com_xmovie/js/video.tracking.youtube.min.js');
                break;
            case '2' :
                // Daily Motion
                $name = 'xmovie-dailymotion';
                $attrs = "width='{$size['width']}{$px}' height='{$size['height']}{$px}' frameborder='0' allowfullscreen";
                $embed = JHtml::iframe($movie -> link, $name, $attrs);

                break;
            case '3' :
                // Meta Cafe
                $name = 'xmovie-metacafe';
                $attrs = "width='{$size['width']}{$px}' height='{$size['height']}{$px}' frameborder='0' allowfullscreen";
                $embed = JHtml::iframe($movie -> link, $name, $attrs);

                break;
            case '4' :
                // My Video depricated
                $embed = "<object style='width:{$size['width']}{$px};height:{$size['height']}{$px};' width='{$size['width']}{$px}' height='{$size['height']}{$px}'>";
                $embed .= "<param name='movie' value='{$movie->link}'></param>";
                $embed .= "<param name='AllowFullscreen' value='true'></param>";
                $embed .= "<param name='AllowScriptAccess' value='always'></param>";
                $embed .= "<param name='autoplay' value='{$autoplay}'></param>";
                $embed .= "<param name='wmode' value='transparent'></param>";
                $embed .= "<embed src='{$movie->link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' autoplay='{$autoplay}' wmode='transparent'></embed>";
                $embed .= "</object>";
                break;
            case '5' :
                // Yahoo Video depricated
                $name = 'xmovie-yahoo';
                $attrs = "width='{$size['width']}{$px}' height='{$size['height']}{$px}' scrolling='no' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen";
                $embed = JHtml::iframe($movie -> link, $name, $attrs);

                break;
            case '6' :
                // Veoh
                $name = 'xmovie-veoh';
                $attrs = "width='{$size['width']}{$px}' height='{$size['height']}{$px}' scrolling='no' frameborder='0' webkitallowfullscreen mozallowfullscreen allowfullscreen";
                $embed = JHtml::iframe($movie -> link, $name, $attrs);
                break;
            case '7' :
                // Vimeo
                $name = 'xmovie-vimeo';
                $attrs = "width='{$size['width']}{$px}' height='{$size['height']}{$px}' frameborder='0' allowfullscreen";
                $embed = JHtml::iframe($movie -> link, $name, $attrs);

                break;
            case '8' :
                // Watch Me TV Depricated
                $embed = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' id='external55fa6b030b5add10de4e5c8d6ae8b5ff' codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,115,0' width='{$size['width']}{$px}' height='{$size['height']}{$px}' align='middle'>";
                $embed .= "<param name='movie' value='{$movie->link}'></param>";
                $embed .= "<param name='allowScriptAccess' value='always' />";
                $embed .= "<param name='autoplay' value='{$autoplay}'></param>";
                $embed .= "<param name='wmode' value='transparent'></param>";
                $embed .= "<embed src='{$movie->link}' type='application/x-shockwave-flash' width='{$size['width']}{$px}' height='{$size['height']}{$px}' allowScriptAccess='always' autoplay='{$autoplay}' wmode='transparent'></embed>";
                $embed .= "</object>";
                break;
            case '9' :
                // DIVX Local
                $link = $baseurl . DS . $movie -> link;
                $embed = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embed .= "<param name='custommode' value='none' />";
                $embed .= "<param name='autoPlay' value='{$autoplay}' />";
                $embed .= "<param name='src' value='{$link}' />";
                $embed .= "<embed type='video/divx' src='{$link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}'  autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embed .= "</embed>";
                $embed .= "</object>";
                break;
            case '10' :
                // AVI Local
                $link = $baseurl . DS . $movie -> link;

                $embed = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embed .= "<param name='custommode' value='none' />";
                $embed .= "<param name='autoPlay' value='{$autoplay}' />";
                $embed .= "<param name='src' value='{$link}' />";
                $embed .= "<embed type='video/divx' src='{$link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}'  autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embed .= "</embed>";
                $embed .= "</object>";
                break;
            case '11' :
                // MOV Local
                $link = $baseurl . DS . $movie -> link;
                $embed = "<object width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab'>";
                $embed .= "<param name='src' value='{$link}'>";
                $embed .= "<param name='autoplay' value='{$autoplay}'>";
                $embed .= "<param name='controller' value='true'>";
                $embed .= "<embed src='{$link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoplay='{$autoplay}' controller='true' pluginspage='http://www.apple.com/quicktime/download/'></embed>";
                $embed .= "</object>";
                break;
            case '12' :
                // SWF Local
                $link = $baseurl . DS . $movie -> link;
                $embed = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width='{$size['width']}{$px}' height='{$size['height']}{$px}' align='middle'>";
                $embed .= "<param name='allowScriptAccess' value='sameDomain' />";
                $embed .= "<param name='allowFullScreen' value='true' />";
                $embed .= "<param name='movie' value='{$link}' />";
                $embed .= "<param name='quality' value='high' />";
                $embed .= "<param name='wmode' value='transparent' />";
                $embed .= "<param name='bgcolor' value='#ffffff' />";
                $embed .= "<param name='autoplay' value='{$autoplay}'>";
                $embed .= "<embed src='{$link}' quality='high' wmode='transparent' bgcolor='#ffffff' width='{$size['width']}{$px}' height='{$size['height']}{$px}' align='middle' allowScriptAccess='sameDomain' allowFullScreen='false' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' autoplay='{$autoplay}' />";
                $embed .= "</object>";
                break;
            case '13' :
                // FLV Local
                $link = $baseurl . DS . $movie -> link;

                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'flv', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

				$embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf,  $analytics, 'flv');
                break;
            case '14' :
                // F4V Local
                $link = $baseurl . DS . $movie -> link;

                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'f4v', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

                $embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf,  $analytics, 'f4v');
                break;
            case '15' :
                // WMV Local
                $link = $baseurl . DS . $movie -> link;
                $embed = "<OBJECT id='mediaPlayer' width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701' standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>";
                $embed .= "<param name='fileName' value='{$link}'>";
                $embed .= "<param name='animationatStart' value='true'>";
                $embed .= "<param name='transparentatStart' value='true'>";
                $embed .= "<param name='autoStart' value='{$autoplay}'>";
                $embed .= "<param name='showControls' value='true'>";
                $embed .= "<param name='loop' value='false'>";
                $embed .= "<EMBED type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1' bgcolor='darkblue' showcontrols='true' showtracker='-1' showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='{$size['width']}{$px}' height='{$size['height']}{$px}' src='{$link}' autostart='{$autoplay}' designtimesp='5311' loop='false'>";
                $embed .= "</EMBED>";
                $embed .= "</OBJECT>";
                break;
            case '16' :
                // MP4 Local
                $link = $baseurl . DS . $movie -> link;

                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'mp4', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

                $embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf,  $analytics, 'mp4');

                break;
            case '17' :
            // RM Local
            case '18' :
                // RAM Local
                $link = $baseurl . DS . $movie -> link;
                $embed = "<OBJECT id='rvocx' classid='clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' width='{$size['width']}{$px}' height='{$size['height']}{$px}'>";
                $embed .= "<param name='src' value='{$link}'>";
                $embed .= "<param name='autostart' value='{$autoplay}'>";
                $embed .= "<param name='controls' value='imagewindow'>";
                $embed .= "<param name='console' value='video'>";
                $embed .= "<param name='loop' value='false'>";
                $embed .= "<EMBED src='{$link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' loop='false' type='audio/x-pn-realaudio-plugin' controls='imagewindow' console='video'  autostart='{$autoplay}'>";
                $embed .= "</EMBED>";
                $embed .= "</OBJECT>";
                break;
            case '30' :
                // M4V Local
                $link = $baseurl . DS . $movie -> link;

                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'm4v', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

                $embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf,  $analytics, 'm4v');
                break;
            case '19' :
                // DIVX External
                $embed = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embed .= "<param name='custommode' value='none' />";
                $embed .= "<param name='autoPlay' value='{$autoplay}' />";
                $embed .= "<param name='src' value='{$movie->link}' />";
                $embed .= "<embed type='video/divx' src='{$movie->link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embed .= "</embed>";
                $embed .= "</object>";
                break;
            case '20' :
                // AVI External
                $embed = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embed .= "<param name='custommode' value='none' />";
                $embed .= "<param name='autoPlay' value='{$autoplay}' />";
                $embed .= "<param name='src' value='{$movie->link}' />";
                $embed .= "<embed type='video/divx' src='{$movie->link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embed .= "</embed>";
                $embed .= "</object>";
                break;
            case '21' :
                // MOV External
                $embed = "<object width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab'>";
                $embed .= "<param name='src' value='{$movie->link}'>";
                $embed .= "<param name='autoplay' value='{$autoplay}'>";
                $embed .= "<param name='controller' value='true'>";
                $embed .= "<embed src='{$movie->link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoplay='{$autoplay}' controller='true' pluginspage='http://www.apple.com/quicktime/download/'></embed>";
                $embed .= "</object>";
                break;
            case '22' :
                // SWF External
                $embed = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width='{$size['width']}{$px}' height='{$size['height']}{$px}' align='middle'>";
                $embed .= "<param name='allowScriptAccess' value='sameDomain' />";
                $embed .= "<param name='allowFullScreen' value='true' />";
                $embed .= "<param name='movie' value='{$movie->link}' />";
                $embed .= "<param name='quality' value='high' />";
                $embed .= "<param name='autoplay' value='{$autoplay}'>";
                $embed .= "<param name='wmode' value='transparent' />";
                $embed .= "<param name='bgcolor' value='#ffffff' />";
                $flashvars = '';
                if ($movie -> flashvars != '') {
                    $embed .= "<param name='flashVars' value='{$movie->flashvars}' />";
                    $flashvars = "flashvars='{$movie->flashvars}' ";
                }
                $embed .= "<embed src='{$movie->link}' quality='high' wmode='transparent' bgcolor='#ffffff' {$flashvars} width='{$size['width']}{$px}' height='{$size['height']}{$px}' align='middle' allowScriptAccess='sameDomain' allowFullScreen='false' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' autoplay='{$autoplay}' />";
                $embed .= "</object>";
                break;
            case '23' :
                // FLV External
                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $movie -> link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'flv', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

                $embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf,  $analytics, 'flv');
                break;
            case '24' :
                // F4V External
                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $movie -> link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'f4v', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

                $embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf,  $analytics, 'f4v');
                break;
            case '25' :
                // WMV External
                $embed = "<OBJECT id='mediaPlayer' width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701' standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>";
                $embed .= "<param name='fileName' value='{$movie->link}'>";
                $embed .= "<param name='animationatStart' value='true'>";
                $embed .= "<param name='transparentatStart' value='true'>";
                $embed .= "<param name='autoStart' value='{$autoplay}'>";
                $embed .= "<param name='showControls' value='true'>";
                $embed .= "<param name='loop' value='false'>";
                $embed .= "<EMBED type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1' bgcolor='darkblue' showcontrols='true' showtracker='-1' showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='{$size['width']}{$px}' height='{$size['height']}{$px}' src='{$movie->link}' autoStart='{$autoplay}' designtimesp='5311' loop='false'>";
                $embed .= "</EMBED>";
                $embed .= "</OBJECT>";
                break;
            case '26' :
                // MP4 External
                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $movie -> link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'mp4', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

				$embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf, $analytics, 'mp4');
                break;
            case '27' :
            // RM External
            case '28' :
                // RAM External
                $embed = "<OBJECT id='rvocx' classid='clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' width='{$size['width']}{$px}' height='{$size['height']}{$px}'>";
                $embed .= "<param name='src' value='{$movie->link}'>";
                $embed .= "<param name='autostart' value='{$autoplay}'>";
                $embed .= "<param name='controls' value='imagewindow'>";
                $embed .= "<param name='console' value='video'>";
                $embed .= "<param name='loop' value='false'>";
                $embed .= "<EMBED src='{$movie->link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' loop='false' type='audio/x-pn-realaudio-plugin' controls='imagewindow' console='video' autostart='{$autoplay}'>";
                $embed .= "</EMBED>";
                $embed .= "</OBJECT>";
                break;
            case '31' :
                // M4V External
                if ($format != '' && $format == 'raw') {
                    $rawJson = array('link' => $movie -> link, 'width' => $size['width'] . $px, 'height' => $size['height'] . $px, 'type' => 'm4v', 'player_swf' => $flow_player_swf);
                    return $rawJson;
                }

                $embed = MovieHelper::getFlowPlayerCode($movie, $size['width'], $size['height'], $px, $flow_player_swf,  $analytics, 'm4v');
                break;
            case '29' :
                $embed = $movie -> link;
            default :
                break;
        }

        return $embed;
    }

    public static function getShadowboxCode(&$movie, $num = '', $link = 0, $width = 0, $height = 0, $percent = '')
    {
        $cfgParams = JComponentHelper::getParams('com_xmovie');
        $image_path = JComponentHelper::getParams('com_media') -> get('image_path', 'images');
        $flow_player_swf = JURI::root() . 'components/com_xmovie/js/fp/flowplayer.swf';

        if (!defined(COM_XMOVIE_BASEURL)) {
            $movie_Path = $cfgParams -> get('movie_path');
            $baseurl = JURI::root() . $cfgParams -> get('movie_path');
        } else {
            $baseurl = COM_XMOVIE_BASEURL;
        }

        if ($cfgParams -> get('enable_movie_background')) {
            $urlParse = parse_url($movie -> thumb);
            $thumbPath = JURI::root() . $image_path . DS . $cfgParams -> get('movie_thumb_path');

            if (!array_key_exists('host', $urlParse)) {
                $thumbPath = $thumbPath . DS . $movie -> thumb;
            } else {
                $thumbPath = $movie -> thumb;
            }
        } else {
            $thumbPath = '';
        }

        if ($link) {
            $relLink = '[xmoviesb]';
        } else {
            $relLink = '';
        }
        $autoplay = $cfgParams -> get('cview_autoplay');
        $autoplaystring = "&autoplay={$autoplay}";
        $embed = array();

        if ($width != 0 && $height != 0) {
            $single_max_width = $width;
            $single_max_height = $height;
        } else {
            $single_max_width = $cfgParams -> get('single_max_width');
            $single_max_height = $cfgParams -> get('single_max_height');
        }

        if ($percent == 0) {
            $percent = $cfgParams -> get('pixel_percent');
        }

		$analytics = '';
		$accountId = $cfgParams->get('ganalytics_key');
        $size = MovieHelper::calDimenions($movie -> width, $movie -> height, $single_max_width, $single_max_height, $percent);
		
		if($cfgParams->get('enable_ganalytics') && $accountId !== '') {
			$analytics = MovieHelper::getFlowPlayerAnalytics($accountId);
			$autoplaystring .= '&enablejsapi=1&origin=' . JURI::base();
		}

        switch ($movie->type) {
            case '1' :
                // You Tube
                if ($movie -> flashvars != '') {
                    $movie -> link = $movie -> link . '?' . $movie -> flashvars . urlencode($autoplaystring);
                } else {
                    $movie -> link = $movie -> link . '?' . urlencode($autoplaystring);
                }

                $embed['open'] = '<a href="' . $movie -> link . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $movie -> width . ';height=' . $movie -> height . ';player=swf">';
                $embed['close'] = '</a>';
                break;
            case '2' :
                // Daily Motion
                // Cannot be embedded
                break;
            case '3' :
                // Meta Cafe
                $embed['open'] = '<a href="' . $movie -> link . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $movie -> width . ';height=' . $movie -> height . ';player=swf">';
                $embed['close'] = '</a>';
                break;
            case '4' :
                // My Video	Depricated
                // This will not be an option
                break;
            case '5' :
                // Yahoo Video Depricated
                if ($movie -> flashvars != '') {
                    $movie -> link = $movie -> link . '?' . $movie -> flashvars . $autoplaystring;
                } else {
                    $movie -> link = $movie -> link . '?' . $autoplaystring;
                }

                $embed['open'] = '<a href="' . $movie -> link . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $movie -> width . ';height=' . $movie -> height . ';player=swf">';
                $embed['close'] = '</a>';
                break;
            case '6' :
                // Veoh
                if ($movie -> flashvars != '') {
                    $movie -> link = $movie -> link . '?' . $movie -> flashvars . $autoplaystring;
                } else {
                    $movie -> link = $movie -> link . '?' . $autoplaystring;
                }

                $embed['open'] = '<a href="' . $movie -> link . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $movie -> width . ';height=' . $movie -> height . ';player=swf">';
                $embed['close'] = '</a>';
                break;
            case '7' :
                // PP2G TV	Depricated
                $embed['open'] = '<a href="' . $movie -> link . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $movie -> width . ';height=' . $movie -> height . ';player=swf">';
                $embed['close'] = '</a>';
                break;
            case '8' :
                // Watch Me TV Depricated
                // This will not be supported
                break;
            case '9' :
                // DIVX Local
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $link = $baseurl . DS . $movie -> link;
                $embedded = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embedded .= "<param name='custommode' value='none' />";
                $embedded .= "<param name='autoPlay' value='{$autoplay}' />";
                $embedded .= "<param name='src' value='{$link}' />";
                $embedded .= "<embed type='video/divx' src='{$link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embedded .= "</embed>";
                $embedded .= "</object>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '10' :
                // AVI Local
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $link = $baseurl . DS . $movie -> link;
                $embedded = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embedded .= "<param name='custommode' value='none' />";
                $embedded .= "<param name='autoPlay' value='{$autoplay}' />";
                $embedded .= "<param name='src' value='{$link}' />";
                $embedded .= "<embed type='video/divx' src='{$link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embedded .= "</embed>";
                $embedded .= "</object>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '11' :
                // MOV Local
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $link = $baseurl . DS . $movie -> link;
                $embedded = "<object width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab'>";
                $embedded .= "<param name='src' value='{$link}'>";
                $embedded .= "<param name='autoplay' value='{$autoplay}'>";
                $embedded .= "<param name='controller' value='true'>";
                $embedded .= "<embed src='{$link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoplay='{$autoplay}' controller='true' pluginspage='http://www.apple.com/quicktime/download/'></embed>";
                $embedded .= "</object>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';

                break;
            case '12' :
                // SWF Local
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $link = $baseurl . DS . $movie -> link;
                $embed['open'] = '<a href="' . $link . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $movie -> width . ';height=' . $movie -> height . '">';
                $embed['close'] = '</a>';
                break;
            case '13' :
                // FLV Local
                $link = $baseurl . DS . $movie -> link;
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<div id='player_flv{$num}' style='width:{$size['width']}{$px}; height:{$size['height']}{$px};'></div><div id='info'></div>";
                $script = "<script type='text/javascript'>
					jQuery(document).ready(function() {
					// Flowplayer installation with Flashembed configuration
					flowplayer('player_flv{$num}', {

    					// our Flash component
    					src: '{$flow_player_swf}',

    					// we need at least this Flash version
    					version: [9, 115],

    					// older versions will see a custom message
    					onFail: function()  {
        				document.getElementById('info').innerHTML =
            			'You need the latest Flash version to see MP4 movies. ' +
            			'Your version is ' + this.getVersion();
    				}

    				// here is our third argument which is the Flowplayer configuration
					}, {
    					clip: {
    						url : '{$link}',
    						autoPlay: {$autoplay},
    						wmode: 'transparent'
    					},
    					canvas: {
							backgroundImage: 'url(" . $thumbPath . ")'
						}
						{$analytics}
					});
					});
				</script>";

                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $script . $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';

                break;
            case '14' :
                // F4V Local
                $link = $baseurl . DS . $movie -> link;
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<div id='player_flv{$num}' style='width:{$size['width']}{$px}; height:{$size['height']}{$px};'></div><div id='info'></div>";
                $script = "<script type='text/javascript'>
					jQuery(document).ready(function() {
					// Flowplayer installation with Flashembed configuration
					flowplayer('player_flv{$num}', {

    					// our Flash component
    					src: '{$flow_player_swf}',

    					// we need at least this Flash version
    					version: [9, 115],

    					// older versions will see a custom message
    					onFail: function()  {
        				document.getElementById('info').innerHTML =
            			'You need the latest Flash version to see MP4 movies. ' +
            			'Your version is ' + this.getVersion();
    				}

    				// here is our third argument which is the Flowplayer configuration
					}, {
    					clip: {
    						url : '{$link}',
    						autoPlay: {$autoplay},
    						wmode: 'transparent'
    					},
    					canvas: {
							backgroundImage: 'url(" . $thumbPath . ")'
						}
						{$analytics}
					});
					});
				</script>";

                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $script . $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';

                break;
            case '15' :
                // WMV Local
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $link = $baseurl . DS . $movie -> link;
                $embedded = "<OBJECT id='mediaPlayer' width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701' standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>";
                $embedded .= "<param name='fileName' value='{$link}'>";
                $embedded .= "<param name='animationatStart' value='true'>";
                $embedded .= "<param name='transparentatStart' value='true'>";
                $embedded .= "<param name='autoStart' value='{$autoplay}'>";
                $embedded .= "<param name='showControls' value='true'>";
                $embedded .= "<param name='loop' value='false'>";
                $embedded .= "<EMBED type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1' bgcolor='darkblue' showcontrols='true' showtracker='-1' showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='{$size['width']}{$px}' height='{$size['height']}{$px}' src='{$link}' autostart='{$autoplay}' designtimesp='5311' loop='false'>";
                $embedded .= "</EMBED>";
                $embedded .= "</OBJECT>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '16' :
                // MP4 Local
                $link = $baseurl . DS . $movie -> link;
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                if ($iPod || $iPhone || $iPad) {
                    $embed = "<video width='{$size['width']}{$px}' height='{$size['height']}{$px}{$px}' controls='{$controls}' autoplay='{$autoplay}' >";
                    $embed .= "<source src='{$link}' type='video/mp4' width:{$size['width']}{$px}; height:{$size['height']}{$px}; autoplay='{$autoplay}'>";
                    $embed .= "</video>";
                } elseif ($android) {
                    $embed = "<video src='{$link}' poster='{$thumbPath}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' controls autoplay='{$autoplay}' >";
                    $embed .= "</video>";
                } else {
                    $embedded = "<div id='player_flv{$num}' style='width:{$size['width']}{$px}; height:{$size['height']}{$px};'></div><div id='info'></div>";
                    $script = "<script type='text/javascript'>
						jQuery(document).ready(function() {
						// Flowplayer installation with Flashembed configuration
						flowplayer('player_flv{$num}', {

	    					// our Flash component
	    					src: '{$flow_player_swf}',

	    					// we need at least this Flash version
	    					version: [9, 115],

	    					// older versions will see a custom message
	    					onFail: function()  {
	        				document.getElementById('info').innerHTML =
	            			'You need the latest Flash version to see MP4 movies. ' +
	            			'Your version is ' + this.getVersion();
	    				}

	    				// here is our third argument which is the Flowplayer configuration
						}, {
	    					clip: {
	    						url : '{$link}',
	    						autoPlay: {$autoplay},
	    						wmode: 'transparent'
	    					},
	    					canvas: {
								backgroundImage: 'url(" . $thumbPath . ")'
							}
							{$analytics}
						});
						});
					</script>";

                    $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                    $embed['open'] = $script . $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                    $embed['close'] = '</a>';
                }
                break;
            case '17' :
            // RM Local
            case '18' :
                // RAM Local
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $link = $baseurl . DS . $movie -> link;
                $embedded = "<OBJECT id='rvocx' classid='clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' width='{$size['width']}{$px}' height='{$size['height']}{$px}'>";
                $embedded .= "<param name='src' value='{$link}'>";
                $embedded .= "<param name='autostart' value='{$autoplay}'>";
                $embedded .= "<param name='controls' value='imagewindow'>";
                $embedded .= "<param name='console' value='video'>";
                $embedded .= "<param name='loop' value='false'>";
                $embedded .= "<EMBED src='{$link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' loop='false' type='audio/x-pn-realaudio-plugin' controls='imagewindow' console='video' autostart='{$autoplay}'>";
                $embedded .= "</EMBED>";
                $embedded .= "</OBJECT>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '19' :
                // DIVX External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embedded .= "<param name='custommode' value='none' />";
                $embedded .= "<param name='autoPlay' value='{$autoplay}' />";
                $embedded .= "<param name='src' value='{$movie->link}' />";
                $embedded .= "<embed type='video/divx' src='{$movie->link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embedded .= "</embed>";
                $embedded .= "</object>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '20' :
                // AVI External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<object classid='clsid:67DABFBF-D0AB-41fa-9C46-CC0F21721616' width='{$size['width']}{$px}' height='{$size['height']}{$px}' codebase='http://go.divx.com/plugin/DivXBrowserPlugin.cab'>";
                $embedded .= "<param name='custommode' value='none' />";
                $embedded .= "<param name='autoPlay' value='{$autoplay}' />";
                $embedded .= "<param name='src' value='{$movie->link}' />";
                $embedded .= "<embed type='video/divx' src='{$movie->link}' custommode='none' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoPlay='{$autoplay}' pluginspage='http://go.divx.com/plugin/download/'>";
                $embedded .= "</embed>";
                $embedded .= "</object>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '21' :
                // MOV External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<object width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B' codebase='http://www.apple.com/qtactivex/qtplugin.cab'>";
                $embedded .= "<param name='src' value='{$movie->link}'>";
                $embedded .= "<param name='autoplay' value='{$autoplay}'>";
                $embedded .= "<param name='controller' value='true'>";
                $embedded .= "<embed src='{$movie->link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' autoplay='{$autoplay}' controller='true' pluginspage='http://www.apple.com/quicktime/download/'></embed>";
                $embed .= "</object>";
                $embedded = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '22' :
                // SWF External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embed['open'] = '<a href="' . $movie -> link . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $movie -> width . ';height=' . $movie -> height . '">';
                $embed['close'] = '</a>';
                break;
            case '23' :
                // FLV External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<div id='player_flv{$num}' style='width:{$size['width']}{$px}; height:{$size['height']}{$px};'></div><div id='info'></div>";
                $script = "<script type='text/javascript'>
					jQuery(document).ready(function() {
					// Flowplayer installation with Flashembed configuration
					flowplayer('player_flv{$num}', {

    					// our Flash component
    					src: '{$flow_player_swf}',

    					// we need at least this Flash version
    					version: [9, 115],

    					// older versions will see a custom message
    					onFail: function()  {
        				document.getElementById('info').innerHTML =
            			'You need the latest Flash version to see MP4 movies. ' +
            			'Your version is ' + this.getVersion();
    				}

    				// here is our third argument which is the Flowplayer configuration
					}, {
    					clip: {
    						url : '{$movie->link}',
    						autoPlay: {$autoplay},
    						wmode: 'transparent'
    					},
    					canvas: {
							backgroundImage: 'url(" . $thumbPath . ")'
						}
						{$analytics}
					});
					});
				</script>";

                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $script . $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '24' :
                // F4V External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<div id='player_flv{$num}' style='width:{$size['width']}{$px}; height:{$size['height']}{$px};'></div><div id='info'></div>";
                $script = "<script type='text/javascript'>
					jQuery(document).ready(function() {
					// Flowplayer installation with Flashembed configuration
					flowplayer('player_flv{$num}', {

    					// our Flash component
    					src: '{$flow_player_swf}',

    					// we need at least this Flash version
    					version: [9, 115],

    					// older versions will see a custom message
    					onFail: function()  {
        				document.getElementById('info').innerHTML =
            			'You need the latest Flash version to see MP4 movies. ' +
            			'Your version is ' + this.getVersion();
    				}

    				// here is our third argument which is the Flowplayer configuration
					}, {
    					clip: {
    						url : '{$movie->link}',
    						autoPlay: {$autoplay},
    						wmode: 'transparent'
    					},
    					canvas: {
							backgroundImage: 'url(" . $thumbPath . ")'
						}
						{$analytics}
					});
					});
				</script>";

                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $script . $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '25' :
                // WMV External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<OBJECT id='mediaPlayer' width='{$size['width']}{$px}' height='{$size['height']}{$px}' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95' codebase='http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701' standby='Loading Microsoft Windows Media Player components...' type='application/x-oleobject'>";
                $embedded .= "<param name='fileName' value='{$movie->link}'>";
                $embedded .= "<param name='animationatStart' value='true'>";
                $embedded .= "<param name='transparentatStart' value='true'>";
                $embedded .= "<param name='autoStart' value='{$autoplay}'>";
                $embedded .= "<param name='showControls' value='true'>";
                $embedded .= "<param name='loop' value='false'>";
                $embedded .= "<EMBED type='application/x-mplayer2' pluginspage='http://microsoft.com/windows/mediaplayer/en/download/' id='mediaPlayer' name='mediaPlayer' displaysize='4' autosize='-1' bgcolor='darkblue' showcontrols='true' showtracker='-1' showdisplay='0' showstatusbar='-1' videoborder3d='-1' width='{$size['width']}{$px}' height='{$size['height']}{$px}' src='{$movie->link}' autostart='{$autoplay}' designtimesp='5311' loop='false'>";
                $embedded .= "</EMBED>";
                $embedded .= "</OBJECT>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                $embed['close'] = '</a>';
                break;
            case '26' :
                // MP4 External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                if ($iPod || $iPhone || $iPad) {
                    $embed = "<video width='{$size['width']}{$px}' height='{$size['height']}{$px}' controls='{$controls}' autoplay='{$autoplay}' >";
                    $embed .= "<source src='{$movie->link}' type='video/mp4' width:{$size['width']}{$px}; height:{$size['height']}{$px}; autoplay='{$autoplay}'>";
                    $embed .= "</video>";
                } elseif ($android) {
                    $embed = "<video src='{$movie->link}' poster='{$thumbPath}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' controls autoplay='{$autoplay}' >";
                    $embed .= "</video>";
                } else {
                    $embedded = "<div id='player_flv{$num}' style='width:{$size['width']}{$px}; height:{$size['height']}{$px};'></div><div id='info'></div>";
                    $script = "<script type='text/javascript'>
						jQuery(document).ready(function() {
						// Flowplayer installation with Flashembed configuration
						flowplayer('player_flv{$num}', {

	    					// our Flash component
	    					src: '{$flow_player_swf}',

	    					// we need at least this Flash version
	    					version: [9, 115],

	    					// older versions will see a custom message
	    					onFail: function()  {
	        				document.getElementById('info').innerHTML =
	            			'You need the latest Flash version to see MP4 movies. ' +
	            			'Your version is ' + this.getVersion();
	    				}

	    				// here is our third argument which is the Flowplayer configuration
						}, {
	    					clip: {
	    						url : '{$movie->link}',
	    						autoPlay: {$autoplay},
	    						wmode: 'transparent'
	    					},
	    					canvas: {
								backgroundImage: 'url(" . $thumbPath . ")'
							}
							{$analytics}
						});
						});
					</script>";

                    $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                    $embed['open'] = $script . $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . ';height=' . $size['height'] . '">';
                    $embed['close'] = '</a>';
                }
                break;
            case '27' :
            // RM External
            case '28' :
                // RAM External
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $embedded = "<OBJECT id='rvocx' classid='clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' width='{$size['width']}{$px}' height='{$size['height']}{$px}'>";
                $embedded .= "<param name='src' value='{$movie->link}'>";
                $embedded .= "<param name='autostart' value='{$autoplay}'>";
                $embedded .= "<param name='controls' value='imagewindow'>";
                $embedded .= "<param name='console' value='video'>";
                $embedded .= "<param name='loop' value='false'>";
                $embedded .= "<EMBED src='{$movie->link}' width='{$size['width']}{$px}' height='{$size['height']}{$px}' loop='false' type='audio/x-pn-realaudio-plugin' controls='imagewindow' console='video' autostart='{$autoplay}'>";
                $embedded .= "</EMBED>";
                $embedded .= "</OBJECT>";
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$embedded}</div>";

                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . $px . ';height=' . $size['height'] . $px . '">';
                $embed['close'] = '</a>';
                break;
            case '29' :
                $px = '';
                if ($percent == 'pixel') {
                    $px = 'px';
                }
                $size['width'] = $size['width'] + $cfgParams -> html_offset_width;
                $size['height'] = $size['height'] + $cfgParams -> html_offset_height;
                $divcont = "<div id='video-cont{$num}' style='display:none;'>{$movie->link}</div>";
                $embed['open'] = $divcont . '<a href="#video-cont' . $num . '" title="' . htmlspecialchars($movie -> title) . '" rel="lightbox' . $relLink . ';width=' . $size['width'] . $px . ';height=' . $size['height'] . $px . '">';
                $embed['close'] = '</a>';
                break;
            default :
                break;
        }

        return $embed;
    }

	public static function getFlowPlayerCode($movie, $width, $height, $px, $flow_player_swf, $analytic, $type) {
		if($analytic !== '') {
			$analytics = "analytics: '{$analytic}',"; 
		}
		
		$analytics = '';
		
		$params = "{
			playlist: [
				[
					{ {$type}:  '{$movie->link}' }
				]
			],
			{$analytics}
			debug: true,
			width: '{$width}{$px}',
			height: '{$height}{$px}',
			swf: '{$flow_player_swf}'
		}";
                
    	$embed = "<script type='text/javascript'>
					jQuery(document).ready(function() {
						flowplayer.conf.analytics = '{$analytic}';
						var fpApi = jQuery('#player').flowplayer({$params});
					});
				</script>";
		$embed .= "<div id='player' class='functional' title='{$movie->title}'></div>";
		return $embed;
	}
	
	public static function getYoutubePlayerCode($movie, $width, $height, $name) {
		$movieParts = parse_url($movie->link);
		$movieId = basename($movieParts['path']);

		$embed = "<script>
		var tag = document.createElement('script');
		tag.src = 'https://www.youtube.com/iframe_api';
		var firstScriptTag = document.getElementsByTagName('script')[0];
		firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
		
		function onYouTubeIframeAPIReady() {
			VideoTracker.setVideoId('{$name}');
			VideoTracker.setVideoUrl('{$movieId}');
			VideoTracker.setVideoSize({$width}, {$height});
			VideoTracker.initialize('{$movie->title}');
        }
        </script>";

		return $embed;
    }

    public static function getResolvedMovieLink($link) {
        $cfgParams =  JComponentHelper::getParams('com_xmovie');
        $parsedLink = parse_url($link);
                                
        if (!isset($parsedLink['host']) || $parsedLink['host'] == '') {
            if (!defined('COM_XMOVIE_BASEURL')) {
                $baseurl = JURI::root() . $cfgParams -> get('movie_path');
            } else {
                $baseurl = COM_XMOVIE_BASEURL;
            }
    
            $link = $baseurl . DS . $link;
        } 

        return $link;
    }

    public static function getResolvedMovieImage($link) {
        $cfgParams =  JComponentHelper::getParams('com_xmovie');
        $thumbPath = $cfgParams->get('movie_thumb_path', '');
        $resizeThumbs = $cfgParams->get('resize_thumbs');
        $imageThumb = parse_url($link);
        $movString = '';
                                
        if (!isset($imageThumb['host']) || $imageThumb['host'] == '') {
            if ($resizeThumbs) {
                $movString = JURI::base(true)."/components/com_xmovie/helpers/img.php?file=".urlencode($link)."&t=m";                                                    
            } else {
                $movString = JURI::base(true). "/" . $thumbPath . "/" . $link;    
            }
        } else {
            $movString = $link;                        
        } 

        return $movString;
    }
    
    public static function getVideoDimensions($origWidth, $origHeight) {
        $cfgParams = JComponentHelper::getParams('com_xmovie');
        $single_max_width = $cfgParams -> get('single_max_width');
        $single_max_height = $cfgParams -> get('single_max_height');

        $format = JRequest::getString('format', '');
        if ($format != '' && $format == 'raw') {
            $single_max_width = JRequest::getInt('w', '');
            $single_max_height = JRequest::getInt('h', '');
        }

        $size = array('width' => $origWidth, 'height' => $origHeight);

        if (empty($origHeight) || $origHeight == "") {
            $origHeight = $single_max_height;
        }

        if (empty($origWidth) || $origWidth == "") {
            $origWidth = $single_max_width;
        }

        // If the ratio > goal ratio and the width > goal width resize down to goal width
        if (($origWidth / $origHeight) > $single_max_width / $single_max_height && $origWidth > $single_max_width) {
            $size['width'] = $single_max_width;
            $size['height'] = round($single_max_width / $origWidth * $origHeight);
        } else if ($origHeight > $single_max_height) {
            $size['width'] = round($single_max_height / $origHeight * $origWidth);
            $size['height'] = $single_max_height;
        }

        return $size;
    }
	
    public static function calDimenions($origWidth, $origHeight, $maxWidth, $maxHeight, $type = 'pixel')
    {

        $return = array('width' => $origWidth, 'height' => $origHeight);

        if ($type == 'pixel') {
            if (empty($origHeight) || $origHeight == "") {
                $origHeight = $maxHeight;
            }

            if (empty($origWidth) || $origWidth == "") {
                $origWidth = $maxWidth;
            }

            // If the ratio > goal ratio and the width > goal width resize down to goal width
            if (($origWidth / $origHeight) > $maxWidth / $maxHeight && $origWidth > $maxWidth) {
                $return['width'] = $maxWidth;
                $return['height'] = round($maxWidth / $origWidth * $origHeight);
            } else if ($origHeight > $maxHeight) {
                $return['width'] = round($maxHeight / $origHeight * $origWidth);
                $return['height'] = $maxHeight;
            }
        } else {
            $return['width'] = $maxWidth;
            $return['height'] = $maxHeight;
        }

        return $return;
    }

    public static function getXMovieItemId($cid = null)
    {
        $com = JComponentHelper::getComponent('com_xmovie');
        $db = &JFactory::getDBO();

        $query = "SELECT id FROM #__menu WHERE published = '1' AND componentid='{$com->id}' AND link LIKE '%main%' AND client_id = '0' LIMIT 1";
        $db -> setQuery($query);
        $row = $db -> loadObject();

        if (isset($row) && !empty($row)) {
            return $row;
        } else {
            if (!isset($row) || empty($row) && $cid != null) {
                $query = "SELECT id, link FROM #__menu WHERE published = '1' AND componentid='{$com->id}' AND link LIKE '%view=category%' AND client_id = '0";
                $db -> setQuery($query);
                $row = $db -> loadObjectList();

                if (isset($row) || !empty($row)) {
                    foreach ($row as $cRow) {
                        $parentId = '';
                        $url = JURI::getInstance($cRow -> link);
                        $parentId = MovieHelper::isParentId($url -> getVar('id'), $cid, $db);

                        if ($parentId) {
                            $row = new stdClass;
                            $row -> id = $cRow -> id;
                            return $row;
                        }
                    }

                    $row = '';
                    $row = new stdClass;
                    $row -> id = '';
                    return $row;
                } else {
                    $row = '';
                    $row = new stdClass;
                    $row -> id = '';
                    return $row;
                }
            } else {
                $row = '';
                $row = new stdClass;
                $row -> id = '';
                return $row;
            }
        }

        return $row;
    }

    public static function isParentId($id, $cid, $db) {
        if ($id == $cid) {
            return true;
        }

        if ($cid != '') {
            $query = "SELECT pid FROM #__xmovie_categories WHERE id='{$cid}' LIMIT 1";
            $db -> setQuery($query);
            $row = $db -> loadObject();

            if ($row -> pid == $id) {
                return true;
            } else if ($row -> pid == 1 || $row -> pid == 0) {
                return false;
            } else {
                $result = MovieHelper::isParentId($id, $row -> pid, $db);

                if ($result) {
                    return true;
                } else {
                    return false;
                }
            }
        }

        return false;
    }

    public static function getComponentId() {
        $com = JComponentHelper::getComponent('com_xmovie');
        $query = "SELECT id FROM #__menu WHERE published = '1' AND componentid='{$com->id}' AND link LIKE '%main%' AND client_id = '0' LIMIT 1";
        $db = &JFactory::getDBO();
        $db -> setQuery($query);
        $row = $db -> loadObject();

        if (!isset($row) || empty($row)) {
            $row = new stdClass;
            $row -> id = null;
        }

        $currentId = JRequest::getVar('Itemid', '');

        if (isset($row -> id) && $currentId != $row -> id) {
            $row -> id = $currentId;
        } else if ($row -> id == '') {
            $row -> id = $currentId;
        }

        return $row;
    }

    public static function getMovieId($id)
    {
        jimport('joomla.environment.uri');
        $com = JComponentHelper::getComponent('com_xmovie');
        $query = "SELECT id, link FROM #__menu WHERE componentid='{$com->id}' AND link LIKE '%main%' AND client_id = '0'";
        $db = &JFactory::getDBO();
        $db -> setQuery($query);
        $links = $db -> loadObjectList();

        $main = new stdClass;
        $views = array();
        $itemid = '';

        if (count($links) > 0) {
            foreach ($links as $link) {
                $currURI = JURI::getInstance($link -> link);

                if ($currURI -> getVar('view') == 'category') {
                    $itemid = $currURI -> getVar('id');
                    $views[$itemid] = new stdClass;
                    $views[$itemid] -> id = $link -> id;
                } else if ($currURI -> getVar('view') == 'main') {
                    $main -> id = $link -> id;
                } else if ($currURI -> getVar('view') != 'single') {
                    $main -> id = $link -> id;
                }
            }
        }

        if (array_key_exists($id, $views)) {
            return $views[$id];
        } else {
            return $main;
        }
    }

    public static function setCookieParams()
    {
        $cfgParams = JComponentHelper::getParams('com_xmovie');

        $expire = time() + 60 * 60;
        $path = '/';
        $image_path = JComponentHelper::getParams('com_media') -> get('image_path', 'images') . '/';

        if (!defined('COM_XMOVIE_BASE')) {
            $baseDir = JPATH_ROOT . DS . $image_path . $cfgParams -> get('movie_thumb_path');
        } else {
            $baseDir = COM_XMOVIE_BASE;
        }

        $pObject = (object) array();

        $pObject -> admin_img_width = $cfgParams -> get('rWidth_admin');
        $pObject -> admin_img_height = $cfgParams -> get('rHeight_admin');
        $pObject -> mov_img_width = $cfgParams -> get('cview_mov_width');
        $pObject -> mov_img_height = $cfgParams -> get('cview_mov_height');
        $pObject -> base_dir = $baseDir;

        $fileParams = serialize($pObject);
        $fileParams = gzcompress($fileParams);
        $fileParams = base64_encode($fileParams);

        setCookie('xmovie_cookie', $fileParams, $expire, $path);
    }

    public static function getCategory($id)
    {
        $query = "SELECT cid FROM #__xmovie_movies WHERE published = '1' AND id='{$id}' LIMIT 1";
        $db = &JFactory::getDBO();
        $db -> setQuery($query);
        $row = $db -> loadObject();
        return $row;
    }

    public static function getCategorySlug()
    {
        $app = JComponentHelper::getParams('com_xmovie');
        $cfgParams = $app -> get('params');
        $alias = $cfgParams -> cat_alias_name;

        return $alias;
    }

    public static function getMovieSlug()
    {
        $app = JComponentHelper::getParams('com_xmovie');
        $cfgParams = $app -> get('params');
        $alias = $cfgParams -> mov_alias_name;

        return $alias;
    }

    public static function getPixelToEm($pixel = '', $base = 16)
    {
        $ems = (1 / $base) * $pixel;
        return $ems;
    }

    public static function getCategoryTree($data, $tree, $id = 0, $currentId)
    {

        // Ordering
        $countItemsInCat = 0;
        foreach ($data as $key) {
            static $iCT = 0;
            // All displayed items

            if ($key -> pid == $id && $currentId != $id && $currentId != $key -> id) {

                $tree[$iCT] = new JObject();

                // Ordering MUST be solved here
                if ($countItemsInCat > 0) {
                    $tree[$iCT] -> orderup = 1;
                } else {
                    $tree[$iCT] -> orderup = 0;
                }

                if ($countItemsInCat < ($key -> countid - 1)) {
                    $tree[$iCT] -> orderdown = 1;
                } else {
                    $tree[$iCT] -> orderdown = 0;
                }

                $tree[$iCT] -> id = $key -> id;
                $tree[$iCT] -> pid = $key -> pid;
                $tree[$iCT] -> name = $key -> name;
                $tree[$iCT] -> thumb = $key -> thumb;
                $tree[$iCT] -> hits = $key -> hits;
                $tree[$iCT] -> banner = $key -> banner;
                $tree[$iCT] -> quicktake = $key -> quicktake;
                $tree[$iCT] -> description = $key -> description;
                $tree[$iCT] -> access = $key -> access;
                $tree[$iCT] -> groupname = $key -> groupname;
                $tree[$iCT] -> creation_date = $key -> creation_date;
                $tree[$iCT] -> published = $key -> published;
                $tree[$iCT] -> ordering = $key -> ordering;
                $tree[$iCT] -> metakey = $key -> metakey;
                $tree[$iCT] -> metadesc = $key -> metadesc;
                $tree[$iCT] -> metaauthor = $key -> metaauthor;
                $tree[$iCT] -> metarobots = $key -> metarobots;

                $iCT++;

                $tree = MovieHelper::getCategoryTree($data, $tree, $key -> id, $currentId);
                $countItemsInCat++;
            }
        }

        return ($tree);
    }

}
