<?php
/**
 * @version $Id: superXMVC.php 139 2010-01-03 20:45:41Z  $
 * @package Blue Flame Framework (bfFramework)
 * @copyright Copyright (C) 2003,2004,2005,2006,2007,2008,2009 Blue Flame IT Ltd. All rights reserved.
 * @license GNU General Public License
 * @link http://www.blueflameit.ltd.uk
 * @author Phil Taylor / Blue Flame IT Ltd.
 *
 * bfFramework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * bfFramework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this package.  If not, see http://www.gnu.org/licenses/
 */
defined ( '_JEXEC' ) or die ( 'Restricted access' );

/* if we forgot to include the framework */
if (! function_exists ( 'bfLoad' )) {
	/* Pull in the bfFramework */
	include (JPATH_ROOT . DS . 'mambots' . DS . 'system' . DS . 'blueflame' . DS . 'bfFramework.php');
}
if (_BF_PLATFORM == 'JOOMLA1.5') {
	$mainframe = JFactory::getApplication ();
} else {
	global $mainframe;
}
bfLoad ( 'bfController' );
bfLoad ( 'bfModel' );

if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
@date_default_timezone_set(@date_default_timezone_get());

/**
 * Pull in and set up the controller
 * run quick security test
 */
if (defined ( '_XAJAX_ADMIN' )) {
	
	/* Include our admin controller */
	require ($registry->getValue ( 'bfFramework_' . $mainframe->get ( 'component_shortname' ) . '.controller.admin' ));
	
	/* Check the name of the xfunction */
	if (bfSecurity::checkXFunction ( $args ) === false) {
		/* Display popup alert */
		$objResponse->alert ( bfText::_ ( 'code(30), Access Denied to ' ) . bfSecurity::cleanVar ( $args [0], 0 ) );
		return $objResponse;
	}

} else {
	
	/* Include our front controller */
	require ($registry->getValue ( 'bfFramework_' . $mainframe->get ( 'component_shortname' ) . '.controller.front' ));
	
	/* Check the name of the xfunction */
	if (bfSecurity::checkXPublicFunction ( $args ) === false) {
		/* Display popup alert */
		$objResponse->alert ( bfText::_ ( 'code(58), Access Denied to ' ) . bfSecurity::cleanVar ( $args [0], 0 ) );
		return $objResponse;
	}
}

/* Get our task from xAJAX, its the first in the args array */
$task = ( string ) array_shift ( $args );

/* Security Check */
$task = ( string ) bfSecurity::cleanVar ( $task, 0 );

/* Set our session mode */
$session->setMode ( $task );

/* Make a controller instance and provide some sensible defaults */
$controller_class = $mainframe->get ( 'component' ) . 'Controller';
if (! class_exists ( $controller_class ))
	$controller_class = $mainframe->get ( 'component' ) . 'ControllerFront';
$controller = new $controller_class ( );
/* @var $controller JController */

/* Pass the controller incoming args */
$controller->setArguments ( $args );

/* push xAJAX ObjResponse into controller */
$controller->xajax = $objResponse;

/* If the execute cannot find xfoo in the controller it sets view as foo */
$taskresult = $controller->execute ( $task );

/* error checking - if we dont have a view we dont know what to do! */
$view = $controller->getView ();

/* If we have no view then try the task name as a view name */
if (! isset ( $view ) || $view == '')
	$view = $task;
	
/* Set the view name */
$session->set ( 'view', $view );

/*
* If this is an index then we need to know where to return to
* if we save or cancel an edit or change the filter states
*/
$session->set ( 'lastview', $controller->getView () );

/* Deal with the layout/view or just return some xajax actions*/
switch ($controller->getLayout ()) {
	
	case 'simple' :
		$simple = true;
		break;
	case "embed":

		/* stop loading menus etc... */
		$registry->setValue ( 'isEmbed', 1 );
		
		/* Get the view, load it, parse it and get HTML back */
		$html = $controller->renderView ();
		
		/* draw/set the Main DIV area with our view */
		$controller->xajax->assign ( $controller->getXajaxTarget (), "innerHTML", $html );
		
		break;
	
	case 'none' :
		break;
	
	case 'error' :
		$controller->xajax->alert ( 'Error: (' . $registry->getValue ( 'errno' ) . ') ' . $registry->getValue ( 'error' ) );
		break;
	
	case 'text' :
		$action = $controller->getXajaxAction ();
		$controller->xajax->$action ( $controller->getXajaxTarget (), "innerHTML", $controller->getMessage () );
		break;
	
	case 'html' :
	case 'view':
		/* Get the view, load it, parse it and get HTML back */
		$html = $controller->renderView ();
		
		/* draw/set the Main DIV area with our view */
		$controller->xajax->assign ( $controller->getXajaxTarget (), "innerHTML", $html );
		
		/* if admin draw console */
		if (bfCompat::isAdmin ()) {
			
			/* Tool Bar Buttons */
			$toolbar = $controller->getToolbar ( $task, true );
			$controller->xajax->assign ( 'bftoolbar', "innerHTML", $toolbar );
			
			/* HTML <title> tag */
			$controller->xajax->script ( 'document.title="' . $controller->getPageTitle ( $task ) . '";' );
			
			/* Set the Page Header */
			//			 $controller->xajax->assign('bfHeader','innerHTML',$controller->getPageHeader());
			$controller->xajax->script ( " jQuery('div#bfHeader').html('" . $controller->getPageHeader () . "'); " );
		}
		
		/* See if we need to run more javascript */
		/* @TODO Hack in to controller */
		//
		$usedTabs = $registry->getValue ( 'usedTabs' );
		if ($usedTabs) {
			$controller->xajax->script ( 'jQuery(\'#bfTabs\').tabs();' );
		}
		
		$hasPopups = $registry->getValue ( 'hasPopups' );
		if ($hasPopups) {
			$controller->xajax->script ( 'jQuery(document).ready(bfinit);' );
		}
		
		$hideleftmenu = $registry->getValue ( 'hideleftmenu' );
		if ($hideleftmenu) {
			$controller->xajax->script ( "jQuery('#leftmenu').hide();" );
		}
		
		if (bfCompat::isAdmin ()) {
			$controller->xajax->script ( "scroll(0,0);" );
		}
		
		if (@$controller->lastscript) {
			$controller->xajax->script ( $controller->lastscript );
		}
		
		break;
	
	case 'xml' :
		// Not implemented yet but you probably only need to
		// point to an XML generating php file in the view directory.
		break;

}

/**
 * Init textareas into Editor Areas
 * fudge as TinyMCE is funny - see http://tinymce.moxiecode.com/punbb/viewtopic.php?pid=11534
 */
if (bfCompat::isAdmin ()) {
	$areas = $controller->getEditorAreas ();
	if ($areas) {
		$scr = 'tinyMCE.idCounter=0;';
		foreach ( $areas as $area ) {
			$scr .= "tinyMCE.execCommand('mceAddControl', true, '" . $area . "');";
		}
		$controller->xajax->script ( $scr );
	}
	$requestAreas = $registry->getValue ( 'editor_used_insmarty', '', 'default' );
	if ($requestAreas) {
		$scr = 'tinyMCE.idCounter=0;';
		foreach ( $requestAreas as $area ) {
			$scr .= "tinyMCE.execCommand('mceAddControl', true, '" . $area . "');";
		}
		$controller->xajax->script ( $scr );
	}
}
/* append to the objResponse any Alert message */
/* @var $controller bfController */
$msg = $controller->getxAJAXAlert ();
if ($msg) {
	$type = $msg [0];
	$text = $msg [1];
	
	$script = ' jQuery(\'div#tag-message\').html(\'<div class="' . $type . '">' . $text . '</div>\');
				jQuery(\'div#tag-message\').css(\'top\',getScrollHeight()' . (bfCompat::isAdmin () ? '-400' : '+200') . ');
			 	jQuery(\'div#tag-message\').show();
		 		window.setTimeout(function(){ jQuery(\'div#tag-message\').hide(); } , 2000);
				';
	$controller->xajax->script ( $script );

}

if ($task != 'xkeepalive' && bfCompat::isAdmin () && ! isset ( $simple )) {
	/* fix mootools */
	$script = 'bf_fixTips();';
	$controller->xajax->script ( $script );
}

/* load thickbox JS init */
if ($registry->getValue ( 'thickbox', false ) === true) {
	$controller->xajax->script ( 'jQuery(document).ready(bfinit);' );
}

/* load scripts */
$scr = $registry->getValue ( 'script', null );
if ($scr !== null) {
	$controller->xajax->script ( "jQuery(document).ready(function(){ " . $scr . " } );" );
}

/* IMPORTANT :: CLOSE THE SESSION - This saves the session back to the db or file */
if (_BF_PLATFORM == 'JOOMLA1.5')
	JSession::close ();