<?php
// $Id$

/**
 * @file
 * TODO: Enter file description here.
 */

/**
 * Implementation of hook_block().
 */
function hcc_business_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0]['info'] = t('Business Directory');
    $blocks[1]['info'] = t('Highest Rated Businesses');
    // OPTIONAL: Add additional block descriptions here, if required.
    return $blocks;
  }
  else if ($op == 'configure') {
    // OPTIONAL: Enter form elements to add to block configuration screen, if required.    
  }
  else if ($op == 'save') {
    // OPTIONAL: Add code to trigger when block configuration is saved, if required.
  }
  else if ($op == 'view') {
    switch ($delta) {
      case 0:
        $items = array();
        $result = db_query('SELECT n.nid FROM {hcc_business} b INNER JOIN {node} n ON b.nid = n.nid WHERE n.status = 1 ORDER BY n.changed DESC');
        while ($node = db_fetch_object($result)) {
          $node = node_load($node->nid);
          $items[] = l($node->title, 'node/'. $node->nid);
        }
        $block['subject'] = t('Recent Business Listings');
        $block['content'] = theme('item_list', $items);
        return $block;
      case 1:
        $items = array();
        $result = db_query('SELECT nid FROM {hcc_business}');
        $nodes = array();
        while ($node = db_fetch_object($result)) {
          $node = node_load($node->nid);
          $nodes[] = array('nid'=>$node->nid, 'title'=>$node->title, 'rating'=>$node->rating);
        }
        usort($nodes, '_hcc_business_rating_sort');
        foreach($nodes as $node){
        	$items[] = l($node['title'], 'node/'. $node['nid']) . ' (' . number_format($node['rating'],1) . '/10)';
        }
        $block['subject'] = t('Highest Rated Businesses');
        $block['content'] = theme('item_list', $items);
        return $block;
      // OPTIONAL: Enter additional cases for each additional block, if defined.
    }
    return $block;
  }
}

function _hcc_business_rating_sort($a, $b)
{
	if($a['rating']==$b['rating']){
		return( strnatcasecmp($a['title'], $b['title']));
	}else{
		return( ($a['rating'] > $b['rating'] ) ? -1 : 1);
	}
}

/**
 * Implementation of hook_help().
 */
function hcc_business_help($section) {
  switch ($section) {
    case 'admin/help#hcc_business':
      return t('Business Node');
    case 'admin/modules#description':
      return t('Business Node');
    case 'node/add#hcc_business':
      return t('Register a new business/organization so that it may be rated and reviewed.');
    // OPTIONAL: Add additional cases for other paths that should display help text.
  }
}


/**
 * Implementation of hook_menu().
 */
function hcc_business_menu($may_cache) {
  $items = array();

  if ($may_cache) {
    $items[] = array(
      'path' => 'node/add/hcc_business',
      'title' => t('Business Node'),
      'access' => user_access('create Business Node'),
      // OPTIONAL: Fill in other properties
    );
    // OPTIONAL: Fill in additional static menu items
  }
  // OPTIONAL: Put in else statement for dynamic menu items that can't be cached.

  return $items;
}


/**
 * Implementation of hook_nodeapi().
 */
function hcc_business_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  switch ($op) {
    case 'delete revision':
      // TODO: Enter revision deletion query here, for example:
      // db_query('DELETE FROM {node_example} WHERE vid = %d', $node->vid);
      break;
  }
}


/**
 * Implementation of hook_perm().
 */
function hcc_business_perm() {
  return array('create Business Node', 'edit own Business Node');
}


/**
 * Implementation of hook_access().
 */
function hcc_business_access($op, $node) {
  global $user;

  if ($op == 'create') {
    return user_access('create Business Node');
  }

  if ($op == 'update' || $op == 'delete') {
    if (user_access('edit own Business Node') && ($user->uid == $node->uid)) {
      return TRUE;
    }
  }
}


/**
 * Implementation of hook_delete().
 */
function hcc_business_delete(&$node) {
  // TODO: Enter database deletion query here, for example:
  // db_query('DELETE FROM {node_example} WHERE nid = %d', $node->nid);
  db_query('DELETE FROM {hcc_business} WHERE nid = %d', $node->nid);
}


/**
 * Implementation of hook_form().
 */
function hcc_business_form(&$node, &$param) {
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#required' => TRUE,
    '#default_value' => $node->title,
    '#weight' => -5
  );
  $form['body'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
    '#default_value' => $node->body,
    '#rows' => '10',
    '#required' => FALSE
  );
//  $form['body_filter']['filter'] = filter_form($node->format);

  	$form['keywords'] = array(
  		'#type'	=> 'textfield',
		'#title' => t('Keywords'),
		'#default_value' => $node->keywords,
		'#required' => FALSE,
		'#weight' => 1);
	$form['chamber_member'] = array(
  		'#type'	=> 'checkbox',
		'#title' => t('Chamber of Commerce Member'),
		'#default_value' => $node->chamber_member,
		'#required' => FALSE,
		'#weight' => 6);
  	$form['url'] = array(
  		'#type'	=> 'textfield',
		'#title' => t('Website URL'),
		'#default_value' => $node->url,
		'#required' => FALSE,
		'#weight' => 3);
  	$form['email'] = array(
  		'#type'	=> 'textfield',
		'#title' => t('Email Address'),
		'#default_value' => $node->email,
		'#required' => FALSE,
		'#weight' => 4);
  	$form['contact'] = array(
  		'#type'	=> 'textfield',
		'#title' => t('Contact Person'),
		'#default_value' => $node->contact,
		'#required' => FALSE,
		'#weight' => 5);
    $form['address1'] = array(
		'#type' => 'fieldset',
		'#title' => t('Primary Address'),
		'#weight' => 10,
		'#collapsible' => TRUE,
		'#collapsed' => TRUE );
	$form['address1']['address1_line1'] = array(
		'#type' => 'textfield',
		'#title' => t('Address'),
		'#default_value' => $node->address1_line1,
		'#required' => FALSE,
    	'#size' => 50,
    	'#maxlength' => 50,
		'#weight' => -1);    
	$form['address1']['address1_line2'] = array(
		'#type' => 'textfield',
		'#title' => '',
		'#default_value' => $node->address1_line2,
		'#required' => FALSE,
    	'#size' => 50,
    	'#maxlength' => 50,
		'#weight' => 0);    
	$form['address1']['csz']['address1_city'] = array(
		'#type' => 'textfield',
		'#title' => t('City'),
		'#default_value' => $node->address1_city,
    	'#size' => 50,
    	'#maxlength' => 50,
		'#required' => FALSE);    
	$form['address1']['csz']['address1_state'] = array(
		'#type' => 'textfield',
		'#title' => t('State'),
		'#default_value' => $node->address1_state,
		'#size' => 5,
    	'#maxlength' => 2,
		'#required' => FALSE);    
	$form['address1']['csz']['address1_zip'] = array(
		'#type' => 'textfield',
		'#title' => t('Zip Code'),
		'#default_value' => $node->address1_zip,
		'#size' => 10,
    	'#maxlength' => 10,
		'#required' => FALSE);
	$form['address1']['map']['address1_showmap'] = array(
		'#type' => 'checkbox',
		'#title' => t('Show Map?'),
		'#default_value' => $node->address1_showmap,
		'#required' => FALSE);
	$form['address1']['map']['address1_latitude'] = array(
		'#type' => 'textfield',
		'#title' => t('Latitude'),
		'#default_value' => $node->address1_latitude,
		'#size' => 10,
    	'#maxlength' => 10,
		'#required' => FALSE);
	$form['address1']['map']['address1_longitude'] = array(
		'#type' => 'textfield',
		'#title' => t('Longitude'),
		'#default_value' => $node->address1_longitude,
		'#size' => 10,
    	'#maxlength' => 10,
		'#required' => FALSE);
    $form['address2'] = array(
		'#type' => 'fieldset',
		'#title' => t('Secondary Address'),
		'#weight' => 20,
		'#collapsible' => TRUE,
		'#collapsed' => TRUE );
	$form['address2']['address2_line1'] = array(
		'#type' => 'textfield',
		'#title' => t('Address'),
		'#default_value' => $node->address2_line1,
		'#required' => FALSE,
    	'#size' => 50,
    	'#maxlength' => 50,
		'#weight' => -1);    
	$form['address2']['address2_line2'] = array(
		'#type' => 'textfield',
		'#title' => '',
		'#default_value' => $node->address2_line2,
		'#required' => FALSE,
    	'#size' => 50,
    	'#maxlength' => 50,
		'#weight' => 0);    
	$form['address2']['csz']['address2_city'] = array(
		'#type' => 'textfield',
		'#title' => t('City'),
		'#default_value' => $node->address2_city,
    	'#size' => 50,
    	'#maxlength' => 50,
		'#required' => FALSE);    
	$form['address2']['csz']['address2_state'] = array(
		'#type' => 'textfield',
		'#title' => t('State'),
		'#default_value' => $node->address2_state,
		'#size' => 5,
    	'#maxlength' => 2,
		'#required' => FALSE);    
	$form['address2']['csz']['address2_zip'] = array(
		'#type' => 'textfield',
		'#title' => t('Zip Code'),
		'#default_value' => $node->address2_zip,
		'#size' => 10,
    	'#maxlength' => 10,
		'#required' => FALSE);
	$form['address2']['map']['address2_showmap'] = array(
		'#type' => 'checkbox',
		'#title' => t('Show Map?'),
		'#default_value' => $node->address2_showmap,
		'#required' => FALSE);
	$form['address2']['map']['address2_latitude'] = array(
		'#type' => 'textfield',
		'#title' => t('Latitude'),
		'#default_value' => $node->address2_latitude,
		'#size' => 10,
    	'#maxlength' => 10,
		'#required' => FALSE);
	$form['address2']['map']['address2_longitude'] = array(
		'#type' => 'textfield',
		'#title' => t('Longitude'),
		'#default_value' => $node->address2_longitude,
		'#size' => 10,
    	'#maxlength' => 10,
		'#required' => FALSE);
			
  // TODO: Enter additional form elements

  return $form;
}


/**
 * Implementation of hook_insert().
 */
function hcc_business_insert($node) {
	// TODO: Enter database insertion query here, for example:
	// db_query("INSERT INTO {node_example} (vid, nid, color, quantity) VALUES (%d, %d, '%s', %d)", $node->vid, $node->nid, $node->color, $node->quantity);
  	$fields = array('nid' 				=> "%d",
  					'description'		=> "'%s'",
  					'keywords'			=> "'%s'",
  					'chamber_member'	=> "%d",
  					'url'				=> "'%s'",
  					'email'				=> "'%s'",
  					'contact'			=> "'%s'",
  					'address1_line1'	=> "'%s'",
  					'address1_line2'	=> "'%s'", 
  					'address1_city'		=> "'%s'", 
  					'address1_state'	=> "'%s'", 
  					'address1_zip'      => "'%s'",
  					'address1_latitude'	=> "%f",
  					'address1_longitude'=> "%f",
  					'address1_showmap'	=> "%d",
  					'address2_line1'	=> "'%s'",
  					'address2_line2'	=> "'%s'", 
  					'address2_city'		=> "'%s'", 
  					'address2_state'	=> "'%s'", 
  					'address2_zip'      => "'%s'",
  					'address2_latitude'	=> "%f",
  					'address2_longitude'=> "%f",
  					'address2_showmap'	=> "%d");

	$fields_str = join(',', array_keys($fields));
	$format_str = join(',', $fields);
	foreach($fields as $field=>$format)
	{
		$args[] = $node->$field;
	}
	db_query("INSERT INTO {hcc_business} ({$fields_str}) VALUES ({$format_str})", $args);
	  					
}


/**
 * Implementation of hook_load().
 */
function hcc_business_load($node) {
  // TODO: Obtain and return additional fields added to the node type, for example:
  // $additions = db_fetch_object(db_query('SELECT color, quantity FROM {node_example} WHERE vid = %d', $node->vid));
  // return $additions;
  $result = db_query('SELECT n.nid FROM {hcc_review} r INNER JOIN {node} n ON r.nid = n.nid WHERE n.status = 1 AND r.bid = %d',$node->nid);
  $reviews = array();
  while($review = db_fetch_object($result)){
  	$reviews[] = node_load($review->nid);
  }
  foreach($reviews as $review){
  	$sum += $review->rating;
  	$count++;  	
  }
  $additions = db_fetch_object(db_query('SELECT * FROM {hcc_business} WHERE nid = %d',$node->nid));
  $additions->rating = ($count ? ($sum/$count) : 0);
  $additions->reviews = $reviews;
  return $additions;
}


/**
 * Implementation of hook_node_info().
 */
function hcc_business_node_info() {
  return array('hcc_business' => array('name' => t('Business Node'), 'base' => 'hcc_business'));
}


/**
 * Implementation of hook_update().
 */
function hcc_business_update($node) {
/*  Not needed since we do not support revisions currently
	if ($node->revision) {
    hcc_business_insert($node);
  } else {*/
  	$fields = array('description'		=> "'%s'",
  					'keywords'			=> "'%s'",
  					'chamber_member'	=> "%d",
  					'url'				=> "'%s'",
  					'email'				=> "'%s'",
  					'contact'			=> "'%s'",
  					'address1_line1'	=> "'%s'",
  					'address1_line2'	=> "'%s'", 
  					'address1_city'		=> "'%s'", 
  					'address1_state'	=> "'%s'", 
  					'address1_zip'      => "'%s'",
  					'address1_latitude'	=> "%f",
  					'address1_longitude'=> "%f",
  					'address1_showmap'	=> "%d",
  					'address2_line1'	=> "'%s'",
  					'address2_line2'	=> "'%s'", 
  					'address2_city'		=> "'%s'", 
  					'address2_state'	=> "'%s'", 
  					'address2_zip'      => "'%s'",
  					'address2_latitude'	=> "%f",
  					'address2_longitude'=> "%f",
  					'address2_showmap'	=> "%d");
    // TODO: Enter database update query here, for example:
    // db_query("UPDATE {node_example} SET color = '%s', quantity = %d WHERE vid = %d", $node->color, $node->quantity, $node->vid);

	foreach($fields as $field=>$format)
	{
		$set_fields[] = "{$field} = {$format}";
		$args[] = $node->$field;
	}
	$fields_str = join(',', $set_fields);
	$args[] = $node->nid;
	db_query("UPDATE {hcc_business} SET {$fields_str} WHERE nid = %d", $args);
}


/**
 * Implementation of hook_validate().
 */
function hcc_business_validate(&$node) {
  // TODO: Enter form validation code here
}


/**
 * Implementation of hook_view().
 */
function hcc_business_view(&$node, $teaser = FALSE, $page = FALSE) {
  // TODO: Insert additional code (call to theme functions, etc.) to execute when viewing a node, for example:
  // $node = node_prepare($node, $teaser);
  // $order_info = theme('node_example_order_info', $node);
  // $node->body .= $order_info;
  // $node->teaser .= $order_info;
  $node = node_prepare($node, $teaser);
  $node->body .= theme('hcc_business_body', $node);
  $node->body .= theme('hcc_review_list', $node->reviews);
  $node->body .= l('Add a Review', 'node/add/hcc_review/'.$node->nid);
}

function theme_hcc_business_field($label, $value)
{
	$output .= '<div class="hcc_business_field">'
	         . '<label>'.t($label).'</label>'
	         . '<p>'.$value.'</p>'
	         . '</div>';
	return $output;	
}
function theme_hcc_business_body($node)
{
	$info = theme('hcc_business_field','Website',$node->url);
	$info .= theme('hcc_business_field','Email',$node->email);
	$info .= theme('hcc_business_field','Contact',$node->contact);
	
	$output = theme_box('Contact Information', $info);
	
	$info = '';
	$info .= ($node->address1_line1 ? $node->address1_line1.'<br />' : '');		
	$info .= ($node->address1_line2 ? $node->address1_line2.'<br />' : '');
	$info .= ($node->address1_city ? $node->address1_city.', ' : '');
	$info .= ($node->address1_state ? $node->address1_state.' ' : '');
	$info .= ($node->address1_zip ? $node->address1_zip : '');
	if($info){
		$output .= theme_box('Primary Address', '<div>'.$info.'</div>');
	}

	$info = '';
	$info .= ($node->address2_line1 ? $node->address2_line1.'<br />' : '');		
	$info .= ($node->address2_line2 ? $node->address2_line2.'<br />' : '');
	$info .= ($node->address2_city ? $node->address2_city.', ' : '');
	$info .= ($node->address2_state ? $node->address2_state.' ' : '');
	$info .= ($node->address2_zip ? $node->address2_zip : '');
	if($info){
		$output .= theme_box('Secondary Address', '<div>'.$info.'</div>');
	}

	return $output;
}
