<?php /* $Id */
/**
* Contacts component event handler
* @package Mambo Open Source
* @Copyright (C) 2000 - 2003 Miro International Pty Ltd
* @ All rights reserved
* @ Mambo Open Source is Free Software
* @ Released under GNU/GPL License: http://www.gnu.org/copyleft/gpl.html
* @version $Revision: 1.15 $
**/

// ensure this file is being included by a parent file
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

// ensure user has access to this function
if (!($acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'all' )
		| $acl->acl_check( 'administration', 'edit', 'users', $my->usertype, 'components', 'com_contact' ))) {
	mosRedirect( 'index2.php', _NOT_AUTH );
}

require_once( $mainframe->getPath( 'admin_html' ) );
require_once( $mainframe->getPath( 'class' ) );

$cid = mosGetParam( $_POST, 'cid', array(0) );
if (!is_array( $cid )) {
	$cid = array(0);
}

switch ($task) {

	case "new":
		editContact( '0', $option);
		break;

	case "edit":
		editContact( $cid[0], $option );
		break;

	case "save":
		saveContact( $option );
		break;

	case "remove":
		removeContacts( $cid, $option );
		break;

	case "publish":
		changeContact( $cid, 1, $option );
		break;

	case "unpublish":
		changeContact( $cid, 0, $option );
		break;

	case "orderup":
		orderContacts( $cid[0], -1, $option );
		break;

	case "orderdown":
		orderContacts( $cid[0], 1, $option );
		break;

	default:
		showContacts( $option );
		break;
}

/**
* List the records
* @param string The current GET/POST option
*/
function showContacts( $option ) {
	global $database, $mainframe;

	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "search{$option}", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );

	$where = $search ? " WHERE name LIKE '%$search%'" : "";

	// get the total number of records
	$database->setQuery( "SELECT COUNT(*) FROM #__contact_details $where" );
	$total = $database->loadResult();

	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );

	// get the subset (based on limits) of required records
	$database->setQuery( "SELECT * FROM #__contact_details"
		. "\n$where"
		. "\nORDER BY ordering, name ASC"
		. "\nLIMIT $pageNav->limitstart, $pageNav->limit"
	);
	$rows = $database->loadObjectList();

	HTML_contact::showcontacts( $rows, $pageNav, $search, $option );
}

/**
* Creates a new or edits and existing user record
* @param int The id of the record, 0 if a new entry
* @param string The current GET/POST option
*/
function editContact( $id, $option ) {
	global $database, $my;
	global $mosConfig_absolute_path;

	$row = new mosContact( $database );
	// load the row from the db table
	$row->load( $id );

	if ($id) {
		// do stuff for existing records
	} else {
		// do stuff for new records
		$row->imagepos = 'top';
		$row->ordering = 9999;
	}

	$ipos[] = mosHTML::makeOption( 'top' );
	$ipos[] = mosHTML::makeOption( 'bottom' );

	$iposlist = mosHTML::selectList( $ipos, 'imagepos', 'class="inputbox" size="1"',
		'value', 'text', $row->imagepos );

	$imageFiles = mosReadDirectory( "$mosConfig_absolute_path/images/stories" );
	$images = array(  mosHTML::makeOption( '', 'Select Image' ) );
	foreach ($imageFiles as $file) {
		if (eregi( "bmp|gif|jpg|png", $file )) {
			$images[] = mosHTML::makeOption( $file );
		}
	}

	$imagelist = mosHTML::selectList( $images, 'image', "class=\"inputbox\" size=\"1\""
		. " onchange=\"javascript:if (document.forms[0].image.options[selectedIndex].value!='') {document.imagelib.src='../images/stories/' + document.forms[0].image.options[selectedIndex].value} else {document.imagelib.src='../images/stories/blank.png'}\"",
		'value', 'text', $row->image );


	if ($id) {
		// build the html select list for ordering
		$order = mosGetOrderingList( "SELECT ordering AS value, name AS text"
			. "\nFROM #__contact_details"
			. "\nWHERE published >= 0 ORDER BY ordering"
		);
		$olist = mosHTML::selectList( $order, 'ordering', 'class="inputbox" size="1"',
		'value', 'text', intval( $row->ordering ) );
	} else {
		$olist = "<input type=\"hidden\" name=\"ordering\" value=\"$row->ordering\" />"
		. " New items default to the last place";
	}

	HTML_contact::editcontact( $row, $imagelist, $iposlist, $option, $olist );
}

/**
* Saves the record from an edit form submit
* @param string The current GET/POST option
*/
function saveContact( $option ) {
	global $database, $my;

	$row = new mosContact( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// pre-save checks
	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// save the changes
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	$row->checkin();
	$row->updateOrder();
	if ($row->default_con) {
		$database->setQuery( "UPDATE #__contact_details SET default_con='0' WHERE id <> $row->id AND default_con='1'" );
		$database->query();
	}

	mosRedirect( "index2.php?option=$option" );
}

/**
* Removes records
* @param array An array of id keys to remove
* @param string The current GET/POST option
*/
function removeContacts( &$cid, $option ) {
	global $database;

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM #__contact_details WHERE id IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect( "index2.php?option=$option" );
}

/**
* Changes the state of one or more content pages
* @param array An array of unique category id numbers
* @param integer 0 if unpublishing, 1 if publishing
* @param string The current option
*/
function changeContact( $cid=null, $state=0, $option ) {
	global $database, $my;

	if (count( $cid ) < 1) {
		$action = $publish == 1 ? 'publish' : 'unpublish';
		echo "<script> alert('Select a record to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	$cids = implode( ',', $cid );

	$database->setQuery( "UPDATE #__contact_details SET published='$state'"
	. "\nWHERE id IN ($cids) AND (checked_out=0 OR (checked_out='$my->id'))"
	);
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (count( $cid ) == 1) {
		$row = new mosContact( $database );
		$row->checkin( intval( $cid[0] ) );
	}

	mosRedirect( "index2.php?option=$option" );
}

/** JJC
* Moves the order of a record
* @param integer The increment to reorder by
*/
function orderContacts( $uid, $inc, $option ) {
	global $database;
	$row = new mosContact( $database );
	$row->load( $uid );
	$row->move( $inc, "published >= 0" );

	mosRedirect( "index2.php?option=$option" );
}

?>