<?php


function inserate_menu() {
	$items = array();

	$items['redeem_token/%/%/%'] = array(
    'title' => 'Redeem a token',
    'page callback' => 'inserate_redeem_token',
    'page arguments' => array(1,2,3,4),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );

	$items['redeem_token_ajax/%/%/%'] = array(
    'title' => 'Redeem a token',
    'page callback' => 'redeem_token_ajax',
    'page arguments' => array(1,2,3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );

	$items['confirm_cancellation'] = array(
    'title' => 'Inserat zurückziehen',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('inserate_cancel_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );


	$items['confirm_cancellation_ajax'] = array(
    'title' => 'Inserat zurückziehen',
    'page callback' => 'inserate_cancel_ajax',
    'page arguments' => array(1, 2, 3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );


/**
	$items['confirm_upgrade'] = array(
    'title' => 'Token Paket Upgrade',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('inserate_upgrade_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );
**/


	$items['meine-token'] = array(
    'title' => t('Contact packages and subscription'),
    'page callback' => '_display_token_lists',
    'page arguments' => array(),
    'access arguments' => array('access content'),
	'type' => MENU_NORMAL_ITEM,
	// Page callback, etc. need to be added here.
	);


	$items['meine-token/aktuell'] = array(
    'title' => t('Contact packages and subscription'),
    'page callback' => '_display_token_lists',
    'page arguments' => array(),
    'access arguments' => array('access content'),
    'type' => MENU_LOCAL_TASK,
    );

	$items['nltest'] = array(
    'title' => 'Newsletter Test',
    'page callback' => '_inserate_newsletter',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );

	$items['lineitemtest'] = array(
    'title' => 'Line Item Test',
    'page callback' => '_inserate_lineitem',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );

	$items['meinkonto-benachrichtigungen'] = array(
    'title' => 'Mein Konto - Benachrichtigungen',
    'page callback' => '_meinkonto_benachrichtigungen',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    );

  /*$items['cron-deactivate-test'] = array(
    'title' => 'test',
    'page callback' => '_inserate_check_outdated_inserations',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );*/

	return $items;
}

function inserate_menu_alter(&$items) {
}


function inserate_node_access($node, $op, $account) {
	// not called for user 1!!!

	global $user;
	$type = is_string($node) ? $node : $node->type;

	if($op == 'create' && arg(0)=='node' &&arg(1)=='add' && arg(2)=='branche') {
    $allowed = _inserate_get_allowed_branches($user->uid);
    $visible = _inserate_get_visible_branches($user->uid);

    // but the current edited node can also be visible
    if(is_object($node)) {
      $visible = array_combine($visible, $visible);
      if(isset($visible[$node->nid])) {
        unset($visible[$node->nid]);
      }
    }

		if(count($visible) >= $allowed) {

      // only needed because there would be two messages
      $msg = drupal_get_messages('status');
      $new_msg = 'Dein derzeitiges Abonnement erlaubt keine weiteren Branchenprofile. Um weitere Branchenprofile anzulegen / aktiviere bitte ein neues Abo-Paket.';

      if(!in_array($new_msg, $msg)) {
        drupal_set_message($new_msg);
      }

      drupal_goto('node/add/token-paket');
			return NODE_ACCESS_DENY;
		}
	}

	if(is_object($node) && $node->type == 'inserat' ) {
		$field_cancelled = field_get_items('node', $node, 'field_cancelled');
    if (isset($field_cancelled[0]['value']) && $user->uid != $node->uid )	{
			return NODE_ACCESS_DENY;
		}
	}

	if($type =='company_profile' && $op=='create') {
		$company_profile=user_has_companyprofile($user->uid);

		if(!empty($company_profile) && $company_profile[0]->node_users_nid) {
			return NODE_ACCESS_DENY;
		}
	}

}

function inserate_block_info() {

  $blocks['withdraw_link'] = array(
    'info' => 'Link Zurückziehen',
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['anbieterprofil_contact_data'] = array(
    'info' => 'Anbieterprofil Contact Data',
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['anbieterprofil_contact_button'] = array(
    'info' => 'Anbieterprofil Contact Button',
    'cache' => DRUPAL_NO_CACHE,
  );


  $blocks['block_inserate_my_account'] = array(
    'info' => 'HW My Account Block',
    'cache' => DRUPAL_NO_CACHE,
  );

  $blocks['block_inserate_price'] = array(
    'info' => 'Inserat Price rewrite if empty',
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['block_inserate_smalltitle'] = array(
    'info' => 'Small Inserat additional title',
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['block_inserate_empty_zeitraum'] = array(
    'info' => 'Inserat zeitraum rewrite',
    'cache' => DRUPAL_NO_CACHE,
  );
  $blocks['block_inserate_add_inserat'] = array(
    'info' => t('Advertise project')
  );

  return $blocks;
}

function inserate_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();
  switch ($delta) {
    case 'withdraw_link':
      $block['subject'] = t('Withdraw');
      $block['content'] =  _inserate_display_withdraw_link();
      break;
    case 'anbieterprofil_contact_data':
      $block['subject'] = 'Anbieterprofil Contact Data';
      $block['content'] =  _anbieterprofil_contact_data();
      break;
    case 'anbieterprofil_contact_button':
      $block['subject'] = 'Anbieterprofil Contact Button';
      $block['content'] =  _anbieterprofil_contact_button();
      break;
    case 'block_inserate_my_account':
      $block['subject'] = 'Inserate My Account';
      $block['content'] =  _block_inserate_my_account();
      break;
    case 'block_inserate_price':
      $block['subject'] = 'Price rewrite if empty';
      $block['content'] =  _block_inserate_price();
      break;
    case 'block_inserate_smalltitle':
      $block['subject'] = 'Small additional title display';
      $block['content'] =  _block_inserate_smalltitle();
      break;
    case 'block_inserate_empty_zeitraum':
      $block['subject'] = 'Inserat Zeitraum rewrite';
      $block['content'] =  _block_inserate_empty_zeitraum();
      break;
    case 'block_inserate_add_inserat':
      $block['subject'] = t('Advertise project');
      $block['content'] = inserate_add_inserat_block();
      break;

  }
  return $block;
}

/**
 * Callback for block. Display node_add form for inserat content type.
 */
function inserate_add_inserat_block() {
  if (user_access('create inserat content')) {
    global $user;
    $type = 'inserat';
    module_load_include('inc', 'node', 'node.pages');
    $node = (object) array('uid' => $user->uid, 'name' => (isset($user->name) ? $user->name : ''), 'type' => $type, 'language' => LANGUAGE_NONE, 'render_small_form' => TRUE);
    $form = drupal_get_form($type.'_node_form',$node);
    $form['#attributes']['class'][] = 'node-inserat-form-small';

    return drupal_render($form);
  }

  return;
}

function inserate_form_inserat_node_form_alter(&$form, &$form_state, $form_id) {

  if(isset($form['#node']->render_small_form)) {
    // Hide unwanted fields
    $form['field_status']['#access'] = false;
    $form['field_cancelled']['#access'] = false;
    $form['field_kontakt_telefon']['#access'] = false;
    $form['field_material_vorhanden']['#access'] = false;
    $form['field_zeitraum']['#access'] = false;
    $form['field_upload_m_glicher_fotos']['#access'] = false;
    $form['field_prce_type']['#access'] = false;
    $form['field_inserat_price']['#access'] = false;
    $form['field_inserat_addresse']['#access'] = false;
    $form['field_inserat_description'][LANGUAGE_NONE][0]['#wysiwyg'] = FALSE;

    // Change Checkboxes to select
    $form['field_inserat_branchen'][LANGUAGE_NONE]['#type'] = 'select';

    // Add/change markup
    $form['#prefix'] = '<em class="informations">'. t('You will be contacted by craftsman near your location') .'</em>';
    $form['title']['#title'] = t('What should be done?');
    $form['field_inserat_addresse'][LANGUAGE_NONE][0]['#title'] = '';
    $form['field_inserat_description'][LANGUAGE_NONE][0]['#prefix'] = '';
    $form['field_inserat_description'][LANGUAGE_NONE][0]['#suffix'] = '';
    $form['field_inserat_description'][LANGUAGE_NONE]['#prefix'] = '';
    $form['field_inserat_description'][LANGUAGE_NONE]['#suffix'] = '';

    $form['field_accept_terms'][LANGUAGE_NONE]['#default_value'] = 1;
    $form['field_accept_terms']['#access'] = false;
    $form['field_anforderungen_an_heimwerke']['#access'] = false;

  }
}

/**
 * Implements HOOK_node_insert().
 */
function inserate_node_insert($node) {
	if($node->type == 'application'){

    if($field_inserat_referenz = field_get_items('node', $node, 'field_inserat_referenz')) {
      $inserat = node_load($field_inserat_referenz[0]['target_id']);

      $field_token_einl_sen = field_get_items('node', $node, 'field_token_einl_sen');
      if($field_token_einl_sen[0]['value']) {
        $oldest_package = _inserate_get_oldest_token();

        if($oldest_package) {
          inserate_redeem_token($oldest_package, $node->nid, $inserat->nid, $inserat->uid);
          drupal_set_message(t('Token has been redeemed.'.' '.l('Zurück zum Inserat.', 'node/'.$inserat->nid) ), 'status');
        } else {
          drupal_set_message(t('No valid token package!.'.' '.l('Zurück zum Inserat.', 'node/'.$inserat->nid) ), 'error');
        }
      } else {
        // DIY-311
        // send token, even if no token package exists
        inserate_redeem_token(NULL, $node->nid, $inserat->nid, $inserat->uid);
      }
    }
	}
}

function inserate_node_view($node, $view_mode, $langcode) {
	global $user;
	if($node->type=='application'):

		// User ist inserent
		if($node->uid!=$user->uid) {
			$uid1=$user->uid;
			$uid2=$node->uid;
		} else {
		// User ist handwerker
			$inserat_node=node_load($node->field_inserat_referenz[LANGUAGE_NONE][0]['target_id']);
			$uid1=$user->uid;
			$uid2=$inserat_node->uid;
		}


		$token_exists = _inserate_token_exists($uid1, $uid2);

		if($node->uid==$user->uid) {
			if(!$node->field_status[LANGUAGE_NONE][0]['value']) {

        if(isset($node->content['body'][0]['#markup'])) {
          $node->content['body'][0]['#markup'].='<p><strong>'.
            l(t('Withdraw this application'),'confirm_cancellation_ajax/'.$node->nid)
            .'</strong></p>';
        }

			}
		}
		if($token_exists || $node->uid==$user->uid) {
			// Token existiert oder User ist Verfasser
#			$node->content['body'][0]['#markup'].='<b>TOKEN EXISTS!</b>';

			$applicant=user_load($node->uid);
			$node->content['field_bewerbungstext']['#title']=$text = t("@name writes", array('@name' => $applicant->name ));;

			if(!$token_exists) {
				// User ist Verfasser, es existiert aber kein Token

				$content=t('<b>Zu dieser Bewerbung existiert kein Token. Wollen Sie ein Token einlösen, um dem Auftraggeber Zugriff zu Ihrer Bewerbung zu ermöglichen?</b>');

				$content.=_display_token_lists() ;

				$content.='<div>';
				$content.=l(t('Token Paket kaufen?'), 'node/add/token-paket', array('attributes'=>array('class'=>'button')));
				$content.='</div>';

        if(isset($node->content['body'][0]['#markup'])) {
          $node->content['body'][0]['#markup'].=$content;
        }
			}

		}
		else {
			$content=t('<b>Zu dieser Bewerbung existiert kein Token. Um den Inhalt zu sehen, müssen Sie ein Token einlösen!</b>');

			$content.='<div>';
			$content.=l(t('Token Paket kaufen?'), 'node/add/token-paket', array('attributes'=>array('class'=>'button')));
			$content.='</div>';



			$content.=_display_token_lists() ;
			$node->content['body'][0]['#markup']=$content;
			$node->content['field_bewerbungstext']=array();
		}

	endif;	// application

	return $node;

}

function _anbieterprofil_contact_data() {
	// Block Callback
	global $user;
  $output = '';

	if(!$user->uid) {
		$output.='<div class="small">'.t('Um die Kontaktdaten dieses Users (email-Adresse und/oder Telefonnummer) einsehen zu können, müssen Sie eingeloggt sein!').'</div>';
		$output.=l(t('Login'), 'user/login',
			$options=array(
				'query'=>array(
					'destination'=>'node/'.arg(1)
				)
			)
		);
		return $output;
	}




	$anbieter_uid=arg(2);
	$branche_id=arg(1);
	$anbieter=user_load($anbieter_uid);
	$profile2=profile2_load_by_user($anbieter, 'anbieterprofil');
	$token_exists=_inserate_token_exists($user->uid, $anbieter_uid);

	$contactdata='';
	$contactdata.= '<span class="views-label email">E-Mail: </span>';
	$contactdata.= '<span>'.$anbieter->mail.'</span>';
	$contactdata.= '<br />';

  $phone_value = t('Not available');
  if($profile2 && $field_telefon = field_get_items('profile2', $profile2, 'field_kontakt_telefon')) {
		$phone_value = check_plain($field_telefon[0]['value']);
	}

  $contactdata.= '<span class="views-label telefon">Telefon: </span>';
  $contactdata.= '<span>'. $phone_value .'</span>';

	if($token_exists || $anbieter_uid == $user->uid)	$output.= $contactdata;

	if(!$token_exists && $anbieter_uid != $user->uid)	{

		$oldest_package=_inserate_get_oldest_token ();



		if ($oldest_package) {
			$redeem_token_link=l(t('Token einlösen?'),
			'redeem_token_ajax/'.$oldest_package.'/'.$application_nid.'/'.$inserat_nid.'/'.$anbieter_uid.'/'.$branche_id,
				$options = array(
					'attributes'=>array('class'=>'user_relationships_popup_link')

				  ));

			$output.= t("Kein Token verfügbar. ").$redeem_token_link;
		} else {
			$output.=t('<div class="small">Um die Kontaktdaten dieses Users (email-Adresse und/oder Telefonnummer) einsehen zu können, benötigen Sie ein Token!</div>');
			$output.=l(t('Tokens kaufen'), 'node/add/token-paket');

		}

	}
	return $output;

}

function _anbieterprofil_contact_button() {

	// Block Callback
	global $user;
	$output= '';
	if(!$user->uid) return NULL;

	$anbieter_uid=arg(2);
	$branche_id=arg(1);
	$anbieter=user_load($anbieter_uid);
	$profile2=profile2_load_by_user($anbieter, $type_name = 'anbieterprofil');
	$token_exists=_inserate_token_exists($user->uid, $anbieter_uid);

	$contactdata='';
#	$contactdata.= '<div class="button">Token existiert</div>';

	if($token_exists || $anbieter_uid == $user->uid)	$output.= $contactdata;

	if(!$token_exists && $anbieter_uid != $user->uid)	{

		$oldest_package=_inserate_get_oldest_token ();

		if ($oldest_package) {
			$redeem_token_link=l(t('Kontaktieren'),
			'redeem_token_ajax/'.$oldest_package.'/'.$application_nid.'/'.$inserat_nid.'/'.$anbieter_uid.'/'.$branche_id,
				$options = array(
					'attributes'=>array('class'=>'user_relationships_popup_link button')

				  ));

			$output.= $redeem_token_link;
		} else {
			$output.=
				l(
				t('Kontaktieren'),
				'node/add/token-paket',
				$options = array(
					'attributes'=>array('class'=>'button')
				)
				);

		}

	}
	return $output;

}
function  _block_inserate_price() {
	$nid=check_plain(arg(1));
	$node=node_load($nid);


  if($field_inserat_price = field_get_items('node', $node, 'field_inserat_price')) {
    $price = $field_inserat_price[0]['value'].' &euro;';
  } else {
    $price=t('Keine Angabe');
  }

	return '
	<div class="field field-name-field-inserat-price field-type-number-integer field-label-hidden">
		<div class="field-items">
			<div class="field-item even">
				'.$price.'
			</div>
		</div>
	</div>';
}
function  _block_inserate_smalltitle() {

	$nid=check_plain(arg(1));
	$node=node_load($nid);

  $node_title = '';

  if(isset($node->title)) {
    $node_title = $node->title;
  }

	return '
	<div class="field field-title pane-node-title field-label-inline clearfix">
		<div class="field-label">Titel:&nbsp;</div>
		<div class="field-items">
			<div class="field-item even">'. $node_title .'</div>
		</div>
	</div>';
}

function  _block_inserate_empty_zeitraum() {
	// Also declared in views-view-field--field-zeitraum.tpl.php
	$nid=check_plain(arg(1));
	$node=node_load($nid);

  if($field_zeitraum = field_get_items('node', $node, 'field_zeitraum')) {
    $from_stamp = strtotime($field_zeitraum[0]['value']);
    $to_stamp = strtotime($field_zeitraum[0]['value2']);

    $zeitraum=t('Von')." ". date('d.m.Y', $from_stamp).' '.t('bis')." ". date('d.m.Y', $to_stamp);

    // Only from date
    if($field_zeitraum[0]['value'] == $field_zeitraum[0]['value2'] ) {
      $zeitraum=t('Ab')." ". date('d.m.Y', $from_stamp);
    }

    if($field_zeitraum[0]['value'] == '2000-01-01 00:00:00' ) {
      $zeitraum=t('Bis')." ". date('d.m.Y', $to_stamp);
    }

    if($field_zeitraum[0]['value'] == $field_zeitraum[0]['value2'] && $field_zeitraum[0]['value2']=='2000-01-01 00:00:00') {
      $zeitraum=t('Ab sofort');
    }

  } else {
    $zeitraum=t('Ab sofort');
  }

	return '
	<div class="field field-title pane-node-title field-label-inline clearfix">
		<div class="field-label">Zeitraum:&nbsp;</div>
		<div class="field-items">
			<div class="field-item even">'.$zeitraum.'</div>
		</div>
	</div>';
}





function _inserate_display_withdraw_link() {
	global $user;

  $content = '';

	$node=node_load(check_plain(arg(1)));


	if(!$node->field_status[LANGUAGE_NONE][0]['value'] && $user->uid==$node->uid ) {
			$content='<div class="inserate-zurückziehen-link ws-actionlink">'.
			l(
				t('Withdraw this ad'),
				'confirm_cancellation_ajax/'.$node->nid,
				$options=array(
					'attributes'=>array('class'=>'user_relationships_popup_link')
				)

			).

			'</div>';
	}
	if($node->field_status[LANGUAGE_NONE][0]['value']) {
			$content='<div class="inserate-zurückziehen-link ws-actionlink">'.t('This ad has been cancelled').'</div>';
	}

	return $content;
}


function _display_token_lists() {
	$content='<h3>Kontaktpakete</h3>';
	$content.= views_embed_view('meine_token_pakete','page');
	$content.='<h3>Abonnements</h3>';
	$content.= views_embed_view('meine_token_pakete','page_1');
	return $content;
}


function inserate_token_link($package_nid, $inserat_nid, $application_nid, $target_uid) {
}

function inserate_redeem_token($package_nid, $application_nid = NULL, $inserat_nid = NULL, $target_uid = NULL) {
	global $user;

	// Create new token as interlink btwn inserat - application - token_paket
	$node = new stdClass();
  $node->type = 'diybook_token';
	$node->status = 1;
	$node->uid = $user->uid;
	$node->title = 'Token';
	$node->promote = 0;
	$node->sticky = 0;
	$node->format = 3;
	$node->body = 'Body';
	$node->revision = 0;
	$node->language='und';

  // only of package is not null/false/...
  if($package_nid) {
    $node->field_paket_referenz[LANGUAGE_NONE][0]['target_id']=$package_nid;
  }

  if($application_nid) 	$node->field_application_referenz[LANGUAGE_NONE][0]['target_id']=$application_nid;
	if($inserat_nid)		$node->field_inserat_referenz[LANGUAGE_NONE][0]['target_id']=$inserat_nid;


	$node->field_user_ref_init[LANGUAGE_NONE][0]['target_id']=$user->uid;

	// Einlösung durch Bewerbung
	if($application_nid) {
		$application_node=node_load($application_nid);
		if($user->uid==$application_node->uid) {
			// Handwerker stellt token selbst => Target user ist inserent!
			$inserat_node=node_load($inserat_nid);
			$node->field_user_ref_target[LANGUAGE_NONE][0]['target_id']=$inserat_node->uid;
		} else {
			// Inserent stellt token => Target user ist handwerker!
			$node->field_user_ref_target[LANGUAGE_NONE][0]['target_id']=$application_node->uid;
		}
	} else {
		$node->field_user_ref_target[LANGUAGE_NONE][0]['target_id']=$target_uid;
	}


	node_save($node);

	// Einlösung durch Klick auf Profil/Kontakt anzeigen

	// Subtract Tokens left from Token package
	if($package_nid) {
    $package=node_load($package_nid);
    $package->field_tokens_verbraucht[LANGUAGE_NONE][0]['value']=$package->field_tokens_verbraucht[LANGUAGE_NONE][0]['value']+1;
    $package->field_tokens_uebrig[LANGUAGE_NONE][0]['value']=$package->field_tokens_uebrig[LANGUAGE_NONE][0]['value']-1;
    node_save($package);
  }

	if($application_nid) {
		// create backref to token in application node. should go into hook_node_save
		$application=node_load($application_nid);
		$application->field_token_referenz[LANGUAGE_NONE][0]['target_id']=$node->nid;
      node_save($application);
	}


	drupal_set_message(t('Deine Anfrage wurde erfolgreich gespeichert und an den Inserenten weitergeleitet.'));
   if($application->field_token_einl_sen[LANGUAGE_NONE][0]['value']) {
     drupal_set_message(t('Zusätzlich wurden dem Inserenten Deine Kontaktdaten und die persönliche Nachricht zugestellt.'));
   }



	if($inserat_nid) {
    drupal_goto('node/'.$inserat_nid);
  }
}


function inserate_form_alter(&$form, &$form_state, $form_id) {


	$markup_required=' <span title="Diese Angabe wird benötigt." class="form-required">*</span>';

	if($form['#id']=='views-exposed-form-heimwerker-suchen-page') {
    drupal_add_library('system', 'ui.autocomplete');
#		dpm($form);
#		$form['#info']['filter-search_api_views_fulltext']['label']=$markup_required;
		#$form['#validate'][]='heimwerker_suchen_validate';
	}

	if($form['#id']=='views-exposed-form-inserate-suche-map-page') {
    drupal_add_library('system', 'ui.autocomplete');
#		$form['#info']['filter-search_api_views_fulltext']['label']=$markup_required;
		#$form['#validate'][]='inserate_suchen_validate';
	}


	global $user;


	if($form_id=='change_password_form') {
		$form['submit']['#prefix']='<div class="separator"></div>';
	}
	if($form_id == 'commerce_checkout_form_checkout' || $form_id=='commerce_checkout_form_review') {
		$form['buttons']['continue']['#weight']=99;
		$form['buttons']['continue']['#prefix']='<span class="button-operator">oder</span>';
		$form['buttons']['cancel']['#weight']=1;
		$form['buttons']['cancel']['#prefix']='';
		$form['buttons']['back']['#prefix']='';
	}



	if($form_id == 'commerce_checkout_form_checkout') {

		$form['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['#address']['first_name']="First";
		$last['customer_profile_billing']['commerce_customer_address'][LANGUAGE_NONE][0]['#address']['last_name']='Last';

	}
	if($form_id == 'token_paket_node_form') {


	#	$form['commerce_node_checkout_product']['#type']='checkbox';

		// Prevent user from buying a second abo

		$options=$form['commerce_node_checkout_product']['#options'];
		$abo_status=_inserate_abo_status();

		$cancel_abo_link='';

		$link_1='<input class="cart-button" type="button" id="buy-4" value="Auswählen"/>';
		$link_2='<input class="cart-button" type="button" id="buy-5" value="Auswählen"/>';
		$standard_active='';
		$premium_active='';


		if ($abo_status) {
#			array_pop($form['commerce_node_checkout_product']['#options']);
#			array_pop($form['commerce_node_checkout_product']['#options']);

			// Premium Abo active
			if($abo_status[0]->field_field_product_id[0]['raw']['value']==5 ) {
				$form['help_text'] = array(
					'#markup' => '<div class="helptext">'.t('Abo Pakete stehen nicht zur Auswahl, da Sie bereits ein gültiges Premium Abo Paket besitzen.').'<br />'.l(t('Premium Abo Paket kündigen.'), 'confirm_cancellation/'.$abo_status[0]->_field_data['nid']['entity']->nid).'</div>',
					'#weight' => -1,
				);
				$link_1='<input class="cart-button" type="button" id="buy-4" value="Auswählen" disabled="disabled"/>';
				$link_2='<a class="cart-button" href="'.'/confirm_cancellation/'.$abo_status[0]->_field_data['nid']['entity']->nid.'">
				<input type="button" value="Kündigen" />
				</a>';
				$premium_active='current_subscription';

			}

			// Standard Abo active
			if($abo_status[0]->field_field_product_id[0]['raw']['value']==4 ) {
				$form['#validate'][]='_inserate_validate_cancel_paypal';

/*				$form['help_text'] = array(
					'#markup' => '<div class="helptext">Sie besitzen bereits ein Standard Abo Paket. Um auf ein Premium Abo Paket upzugraden, '.l('kündigen Sie dieses bitte zuvor!', 'confirm_cancellation/'.$abo_status[0]->_field_data['nid']['entity']->nid).'</div>',
					'#weight' => -1,
				);
*/
				$link_1='<a class="cart-button" href="'.'/confirm_cancellation/'.$abo_status[0]->_field_data['nid']['entity']->nid.'">
				<input type="button" value="Kündigen" />
				</a>';
#				$link_2='<input class="cart-button" type="button" id="buy-4" value="Auswählen" disabled="disabled"/>';
#				$link_2='<a class="cart-button" href="'.'/confirm_upgrade/'.$abo_status[0]->_field_data['nid']['entity']->nid.'">
#				<input type="button" value="Upgrade" />
#				</a>';
				$link_2='<input class="cart-button" type="button" id="buy-5" value="Upgrade" />';


				$link_3='
				<div class="cancel-abo-link">
				<input id="checkbox-confirm-cancellation" name="checkbox_confirm_cancellation" value="1"  class="form-checkbox" type="checkbox">
				<label class="option" for="edit-field-confirm-cancellation">'.t('Kündigung bestätigen').'</label>
				</div>';


/*
				$form['field_confirm_cancellation']=array(
					'#type'=>'textfield',
					'#title'=>t('Standard Konto kündigen'),
					'#default_value' => 0
				);
*/
				$standard_active='current_subscription';

			}
		}

		$tmp=array(
			commerce_product_load(1),
			commerce_product_load(2),
			commerce_product_load(3),
			commerce_product_load(4),
			commerce_product_load(5),

		);
		$products=array();
		foreach($tmp as $product) {

      $price_field = field_get_items('commerce_product', $product, 'commerce_price');
			$price=sprintf('%.2f', $price_field[0]['amount']/100);
			$dec=explode('.', $price);

      $max_entries = '';
      if($max_entries_field = field_get_items('commerce_product', $product, 'field_max_brancheneintragungen')) {
        $max_entries = $max_entries_field[0]['value'];
        if($max_entries > 1000) {
          $max_entries='unlimitiert';
        }
      }

      $amount = '';
      if($amount_field = field_get_items('commerce_product', $product, 'field_anzahl_tokens')) {
        $amount = $amount_field[0]['value'];
			  if($amount > 1000) {
          $amount='unlimitiert';
        }
      }

			$products[$product->product_id]=array(
				'euro'=>$dec[0],
				'cent'=>$dec[1],
				'amount'=>$amount,
				'max_entries'=>$max_entries,
			);
		}


$table_abos= '<p>Alle registrierten Benutzer profitieren von den Funktionen des freien Kontos. Doch diybook bietet noch mehr: Du möchtest Anbieterprofile für verschiedene Branchen erstellen, Deine Firma präsentieren oder Top-Platzierungen in den Suchergebnissen erreichen? Dann sichere Dir ein Abonnement, das deinen Bedürfnissen entspricht!</p><p>Hier alle Eigenschaften und Vorzüge der Konto-Modelle im Überblick:</p>' .
 '<br /><div class="product-table overview tokenabos">
	<div class="col descr">
		<div class="row first"><div class="inner"></div></div>
		<div class="row second"></div>
		<div class="row other"><div class="inner">' . 'Überprüfung der Personalien' . '</div></div>
		<div class="row other"><div class="inner">' . 'max. Brancheneintragungen' . '</div></div>
		<div class="row other"><div class="inner">' . 'Intelligente Benachrichtigung bei neuen Inseraten' . '</div></div>
		<div class="row other"><div class="inner">' . 'Top - Platzierung in den Suchergebnissen' . '</div></div>
		<div class="row other"><div class="inner">' . 'Eigene Kontaktdaten an den Auftraggeber senden' . '</div></div>
		<div class="row other"><div class="inner">' . 'Firmenprofil' . '</div></div>
		<div class="row other"><div class="inner">' . 'Anzeige von Inseraten mit höchsten Auftragschancen' . '</div></div>
		<div class="row other last"><div class="inner">' . 'Anzahl der Kontakte' . '</div></div>
		<div class="row other button ';
		if(isset($link_3)) $table_abos.='abo-cancel';
		$table_abos.='"></div>
	</div>

	<div class="col product" id="product-0">
		<div class="row first"><div class="inner">' . 'Das Kostenlose<small>Das Freie</small>' . '</div></div>
		<div class="row second"><div class="inner">0,<span class="medium">0 €</span><br /><span class="micro">/Monat</span></div></div>
		<div class="row other"><div class="inner"><span class="checked" />x</div></div>
		<div class="row other">1</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other">-</div>
		<div class="row other">-</div>
		<div class="row other">-</div>
		<div class="row other">-</div>
		<div class="row other last">-</div>
		<div class="row other button ';
    if(isset($link_3)) $table_abos.='abo-cancel';
		$table_abos.='"></div>
	</div>

	<div class="col product '.$standard_active.'" id="product-4">
		<div class="row first"><div class="inner">Für Engagierte<small>Vorteilsabo</small><div class="current_account">'.t('Meine Wahl!').'</div></div></div>
		<div class="row second">'.$products[4]['euro'].',<span class="medium">'.$products[4]['cent'].' €</span><br /><span class="micro">/Monat</span></div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other">'.$products[4]['max_entries'].'</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other">-</div>
		<div class="row other">-</div>
		<div class="row other last">'.$products[4]['amount'].'</div>
		<div class="row other button ';
    if(isset($link_3)) $table_abos.='abo-cancel';
		$table_abos.='">'.$link_1.'</div>
	</div>

	<div class="col product '.$premium_active.'" id="product-5">
		<div class="row first"><div class="inner">Das Profipaket<small>Premiumabo</small><div class="current_account">'.t('Meine Wahl!').'</div></div></div>
		<div class="row second">'.$products[5]['euro'].'<span class="medium">,'.$products[5]['cent'].' €</span><br /><span class="micro">/Monat</span></div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other">- '.$products[5]['max_entries'].' -</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other"><span class="checked" />x</div>
		<div class="row other last">- '.$products[5]['amount'].' -</div>
		<div class="row other button ';
    if(isset($link_3)) $table_abos.='abo-cancel';
		$table_abos.='">';
		$table_abos.=$link_2;
    if(isset($link_3)) $table_abos.=$link_3;

		$table_abos.='</div>
	</div>


</div>
';


$table_single='<p>Du hast einen Handwerker gefunden, der dein Projekt perfekt ergänzt, und möchtest unverbindlich bei ihm anfragen? Oder Du erhältst Meldungen auf Dein Inserat und suchst nun den direkten Draht? Dann sichere Dir eines unserer Kontakt-Pakete! So kannst du problemlos mit anderen Benutzern in Verbindung treten, und das in einem Ausmaß, das den Erfordernissen deines Projektes am besten entspricht.</p><p>Hier die Modelle im Überblick:</p>'.
'<br /><div class="product-table overview einzeltokens">
	<div class="col descr">
		<div class="row first"></div>
		<div class="row second"></div>
		<div class="row other"><div class="inner">' . 'Anzahl Kontakte' . '</div></div>
		<div class="row other last"><div class="inner">' . 'Gültigkeit' . '</div></div>
		<div class="row other button"></div>
	</div>

	<div class="col product" id="product-1">
		<div class="row first"><div class="inner">' . 'Das Kleine<small>Der Standard</small>' . '</div></div>
		<div class="row second">'.$products[1]['euro'].',<span class="medium">'.$products[1]['cent'].' €</span></div>
		<div class="row other">'.$products[1]['amount'].'</div>
		<div class="row other last">' . '1 Monat' . '</div>
		<div class="row other button"><input class="cart-button" type="button" id="buy-1" value="Auswählen" /></div>
	</div>

	<div class="col product" id="product-2">
		<div class="row first"><div class="inner">' . 'Das Mittlere<small>Die Renovierung</small>' . '</div></div>
		<div class="row second">'.$products[2]['euro'].',<span class="medium">'.$products[2]['cent'].' €</span></div>
		<div class="row other">'.$products[2]['amount'].'</div>
		<div class="row other last">' . '2 Monate' . '</div>
		<div class="row other button"><input class="cart-button" type="button" id="buy-2" value="Auswählen" /></div>
	</div>

	<div class="col product" id="product-3">
		<div class="row first"><div class="inner">' . 'Das Große<small>Die Baustelle</small>' . '</div></div>
		<div class="row second">'.$products[3]['euro'].',<span class="medium">'.$products[3]['cent'].' €</span></div>
		<div class="row other">'.$products[3]['amount'].'</div>
		<div class="row other last">' . '3 Monate' . '</div>
		<div class="row other button"><input class="cart-button" type="button" id="buy-3" value="Auswählen" /></div>
	</div>
</div>
';

		$profile2 = profile2_load_by_user($user, 'anbieterprofil');
		$markup = $table_single . '<h2 class="toke-buy-heading">' . t('Choose the appropriate subscription') . '</h2>' .$table_abos;
		if($profile2) {
      $markup = $table_abos . '<h2 class="toke-buy-heading">' . t('Choose the appropriate contact package') . '</h2>' . $table_single;
    }



		$form['info_table'] = array(
					'#markup' => $markup,
					'#weight' => 1,
				);

	}// token-paket-node-form

	if ($form_id=='user_profile_form'){

    // DIY-233
    // user_profile_form is the form id of normal user page but also on all profile2 forms
    // so dont do stuff on every form
    // thats kind of a workaround but a quick fix
    if(!(isset($form['#user_category']) && $form['#user_category'] == 'intern')) {
      if (isset($form['field_inserat_addresse'][LANGUAGE_NONE][0]['locality_block']['postal_code'])) {
        $form['field_inserat_addresse'][LANGUAGE_NONE][0]['locality_block']['postal_code']['#title'] .= $markup_required;
      }
      $form['field_inserat_addresse'][LANGUAGE_NONE][0]['locality_block']['locality']['#title'].=$markup_required;
      $form['field_inserat_addresse'][LANGUAGE_NONE][0]['country']['#title'].=$markup_required;
      $form['#validate'][]='inserate_user_profile_validate';
    }
	}

	if($form_id == 'profile2_edit_anbieterprofil_form') {
		$form['profile_anbieterprofil']['field_expiry_inserat'][LANGUAGE_NONE]['#title']='';
		$form['profile_anbieterprofil']['field_deactivated_inserat'][LANGUAGE_NONE]['#title']='';
		$form['profile_anbieterprofil']['field_inform_komments'][LANGUAGE_NONE]['#title']='';
		$form['profile_anbieterprofil']['field_voting_inform'][LANGUAGE_NONE]['#title']='';
		$form['profile_anbieterprofil']['field_personal_applications'][LANGUAGE_NONE]['#title']='';

		$form['help_text'] = array(
			'#markup' => '<div class="helptext">'.t('Das erweiterte Profil dient allen Hand- und Heimwerkern dazu ihren Profiltyp auszuwählen, sowie allgemeine für das Anbieterprofil notwendige Informationen angeben zu können.').'</div>',
			'#weight' => -1,
		);


	}

	if($form_id=='user_profile_form' || $form_id=='profile2_edit_anbieterprofil_form' || ($form_id=='branche_node_form' && !$form['nid']['#value'] )) {
		$user_data=user_load($user->uid);

		if(!$user_data->field_anbieter[LANGUAGE_NONE][0]['value']) return;
		// Helper ToolBar bis zum Anlegen des ersten Profils


		$view=views_get_view('meine_branchen');
		$view->set_arguments(array($user->uid));
		$view->execute();
		$anzahl_branchen=count($view->result);
		if($anzahl_branchen) return;		// User has already created a branch. do nothing.


		$options_inactive=array(
			'html'=>true,
			'attributes'=>array(
				'class'=>'inactive',
				'onClick'=>'return false',
			)
		);

		$items=array(
			0=>array(
				'data'=> l (t('General Data'), 'user/'.$user->uid.'/edit'),
				'class'=>array('arrow_first')
			),
			1=>array(
				'data'=>l (t('Extended Profile'), 'profile-anbieterprofil/'.$user->uid.'/edit'),
				'class'=>array('arrow_second')
			),
			2=>array(
				'data'=>l (t('Add branche'), 'node/add/branche'),
				'class'=>array('array_third')
			),
		);

		$profile2=profile2_load_by_user($user, 'anbieterprofil');
		if(!$profile2) {
			$items[2]=	l (t('Add branche'), 'javascript:void(0)', $options_inactive);
		}

		$form['#prefix']= theme('item_list', array('type'=>'ol', 'items'=>$items, 'attributes'=>array('class'=>'menu progress-bar') ));
	}

	######################################
	if ($form_id=='profile2_edit_anbieterprofil_form') {

	}
	######################################

	if($form_id == 'profile2_edit_notifications_form') {
		$form['profile_notifications']['field_expiry_inserat'][LANGUAGE_NONE]['#title']='';
		$form['profile_notifications']['field_ich_m_chte_ber_neuen_bewer'][LANGUAGE_NONE]['#title']='';
	}
	if($form_id == 'profile2_edit_benachrichtigungen_anfragen_form') {
		$form['profile_benachrichtigungen_anfragen']['field_deactivated_inserat'][LANGUAGE_NONE]['#title']='';
		$form['profile_benachrichtigungen_anfragen']['field_voting_inform'][LANGUAGE_NONE]['#title']='';
		$form['profile_benachrichtigungen_anfragen']['field_voting_inform'][LANGUAGE_NONE]['#title']='';
		$form['profile_benachrichtigungen_anfragen']['field_personal_applications'][LANGUAGE_NONE]['#title']='';
		$form['profile_benachrichtigungen_anfragen']['field_inform_komments'][LANGUAGE_NONE]['#title']='';
	}

}

function inserate_form_node_form_alter(&$form, &$form_state, $form_id) {

	global $user;

	if($form_id=='token_paket_node_form') {

		drupal_add_js(drupal_get_path('module', 'inserate'). '/inserate-token-package-form.js');


        if(!$form['title']['#default_value']) {
          $form['title']['#default_value']='Token Paket '.$user->name.' '.date('Y-m-d H:i:s');
        }

		if($user->uid <> 1) {
			$form['title']['#access']=FALSE;
			$form['field_kaufdatum']['#access']=FALSE;
			$form['field_anzahl_tokens']['#access']=FALSE;
			$form['field_ablaufdatum']['#access']=FALSE;
			$form['field_tokens_verbraucht']['#access']=FALSE;
			$form['field_tokens_uebrig']['#access']=FALSE;
			$form['field_abo']['#access']=FALSE;
			$form['field_cancelled']['#access']=FALSE;
			$form['field_user_reference']['#access']=FALSE;
			$form['actions']['submit']['#value']="Add to cart";
			$form['field_product_id']['#access']=FALSE;
		}

	}

	if($form_id=='application_node_form') {

		if($node=node_load(arg(1))) {

      if($user->uid != 1) {
        $form['title']['#access']=FALSE;
      }

      if(!$form['title']['#default_value']) {
        $form['title']['#default_value']='Bewerbung von '.$user->name.' auf '.$node->title;
      }

      // embedded form in inserate node?
      if($node->type != 'application' ) {
        drupal_add_js(drupal_get_path('module', 'inserate'). '/inserate-inline-application-form.js');
        $form['actions']['submit']['#value']=t("Unterstützung anbieten");
        $form['field_token_einl_sen'][LANGUAGE_NONE]['#title']=t('Kontaktdaten und eine persönliche Nachricht senden');

      }

      if($node->type == 'inserat' ) {

  #			drupal_add_js(drupal_get_path('module', 'inserate'). '/redeem-token-checkbox.js');

        $inserat=node_load(arg(1));
        $token_exists=_inserate_token_exists($user->uid, $node->uid);


        if(!$token_exists) {
          $form['field_token_einl_sen']['#access']=FALSE;

          $oldest_package=_inserate_get_oldest_token ();
          if ($oldest_package) {
            $form['field_token_einl_sen']['#access']=TRUE;
            $output='<i>'.t('Profi-Tipp: hast du gewusst, dass das Senden eines personalisierten Textes die Chancen der Kontaktaufnahme um 60% erhöht?').'</i>';

          } else {
            $output='<div class="small">';
            $output.=t('Leider haben Sie keine Token um dem Inserenten eine personalisierte Nachricht zu schicken.');
            $output.='&nbsp;';
            $output.=l('Hier können Sie Token erwerben.', 'node/add/token-paket');
            $output.='</div>';
            $form['field_token_einl_sen']['#access']=FALSE;
          }

          $form['help_text'] = array(
            '#markup' => '<i>'.$output.'</i>',
            '#weight' => 1,
          );
        } else {
          $form['help_text'] = array(
            '#markup' => '<div class="helptext"><i>'.t('Profi-Tipp: hast du gewusst, dass das Senden eines personalisierten Textes die Chancen der Kontaktaufnahme um 60% erhöht?').'</i></div>',
            '#weight' => 1,
          );
        }
      }

      if(!isset($form['field_inserat_referenz'][LANGUAGE_NONE]['#default_value'][0])) 	{
  #			$inserat_nid=check_plain($query['inserat_id']);
        $inserat_nid=check_plain(arg(1));
        $form['field_inserat_referenz'][LANGUAGE_NONE]['#default_value']=array($inserat_nid);
      }

      if($user->uid<>1) {
        $form['field_inserat_referenz'][LANGUAGE_NONE]['#access']=FALSE;
        $form['field_token_referenz'][LANGUAGE_NONE]['#access']=FALSE;
        $form['field_status'][LANGUAGE_NONE]['#access']=FALSE;
        $form['field_cancelled'][LANGUAGE_NONE]['#access']=FALSE;
      }
    }
	}


	if($form_id=='inserat_node_form' ) {
#		drupal_add_js(drupal_get_path('module', 'inserate'). '/inserate-hierarchical-select.js');

		if($user->uid != 1) {
			$form['field_status']['#access']=FALSE;
			$form['field_cancelled']['#access']=FALSE;

		}



		/* dynamic ajax list */
		$dynamic_select_list=dynamic_select_list($form, $form_state);

#		$form['field_experience_parent'][LANGUAGE_NONE]['#ajax'] = array(
#			'callback' => 'dynamic_list_terms_select_list_ajax_callback',
#			'wrapper' => 'field_inserat_branchen-wrapper',
#			'event' => 'change',
#		);
		$form['field_experience_parent'][LANGUAGE_NONE]['#options']=$dynamic_select_list['parents'];
		$form['field_experience_parent']['#access']=FALSE;

		// parents
		$parents=$dynamic_select_list['parents'];
		unset($parents['none']);
		$form['field_inserat_branchen'][LANGUAGE_NONE]['#options']=$parents;

		$form['field_zeitraum'][LANGUAGE_NONE][0]['#title']=t('Zeitraum ab');
#		array_unshift($form['#validate'], '_inserate_zeitraum_validate');
		drupal_add_js(drupal_get_path('module', 'inserate'). '/inserate-zeitraum-validate.js');

	}
	if($form_id=='branche_node_form' ) {

		global $user;
		if(!$form['nid']['#value']) {
			$profile2=profile2_load_by_user($user, 'anbieterprofil');
			if(!$profile2) {
				drupal_set_message('Bitte füllen Sie zuerst Ihre '.l('Allgemeinen Einstellungen', 'profile-anbieterprofil/'.$user->uid.'/edit').' aus!', 'status');
				drupal_access_denied();
			}
		}

#		dpm($form);
		$form['field_erfahrung'][LANGUAGE_NONE][0]['value']['#field_suffix']="in Jahren";
		$form['field_experience_parent'][LANGUAGE_NONE]['#title']='Branche';

		/* dynamic ajax list */
		$dynamic_select_list=dynamic_select_list($form, $form_state);

		$form['field_experience_parent'][LANGUAGE_NONE]['#ajax'] = array(
			'callback' => 'dynamic_list_terms_select_list_ajax_callback',
			'wrapper' => 'field-experience-wrapper',
			'event' => 'change',
		);
		$form['field_experience_parent'][LANGUAGE_NONE]['#options']=$dynamic_select_list['parents'];


		$form['field_experience'][LANGUAGE_NONE]['#options']=$dynamic_select_list['children'];
		$form['field_experience'][LANGUAGE_NONE]['#prefix'] = '<div id="field-experience-wrapper">';
		$form['field_experience'][LANGUAGE_NONE]['#suffix'] = '</div>';

		$form['#validate'][]='branchentextfilter_validate';

#		drupal_add_js(drupal_get_path('module', 'inserate'). '/inserate-hierarchical-select.js');
	}


}

/**
 * Implements HOOK_profile2_insert().
 */
function inserate_profile2_insert($profile) {
  global $user;
  if($profile->type=='anbieterprofil') {
    drupal_set_message(t('Your settings have been updated.'), 'status');

    if(_diy_craftsman_is_craftsman() && !diy_craftsman_get_branches($user->uid)) {
      drupal_goto('branche-erstellen');
    } else {
      drupal_goto('profile-anbieterprofil/'.$user->uid.'/edit');
    }
  }
}

/**
 * Implements HOOK_profile2_update().
 */
function inserate_profile2_update($profile) {
	global $user;
	if($profile->type=='anbieterprofil') {
		drupal_set_message(t('Your settings have been updated.'), 'status');

    if(_diy_craftsman_is_craftsman() && !diy_craftsman_get_branches($user->uid)) {
      drupal_goto('branche-erstellen');
    } else {
      drupal_goto('profile-anbieterprofil/'.$user->uid.'/edit');
    }
	}
	if($profile->type=='notifications') {
		drupal_set_message(t('Your settings have been updated.'), 'status');
		drupal_goto('profile-notifications/'.$user->uid.'/edit');
	}
	if($profile->type=='benachrichtigungen_anfragen') {
		drupal_set_message(t('Your settings have been updated.'), 'status');
		drupal_goto('profile-benachrichtigungen_anfragen/'.$user->uid.'/edit');
	}


}

function _inserate_tokenform_submit(&$form, &$form_state) {
}


function _inserate_zeitraum_validate($form, &$form_state) {


	if(!$form_state['input']['field_zeitraum'][LANGUAGE_NONE][0]['value']['date']) {

	}
}



function branchentextfilter_validate($form, &$form_state) {
	$text=$form_state['values']['field_erfahrung_beschr'][LANGUAGE_NONE][0]['value'];
	// URL Filter
	$text = preg_replace('@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@', '----', $text);

	// email Filter
	$text = preg_replace("/[^@\s]*@[^@\s]*\.[^@\s]*/", '----', $text);
	$form_state['values']['field_erfahrung_beschr'][LANGUAGE_NONE][0]['value']=$text;


}

/*function heimwerker_suchen_validate($form, &$form_state) {
	if (!$form_state['input']['search_api_views_fulltext'] || !$form_state['input']['address']) {
    $msg = drupal_get_messages('status');
    $new_msg = t('Bitte geben Sie sowohl einen Suchbegriff wie "Maler" oder "Maurer" und den Ort an welchem dieser benötigt ist ein.');

    if(!in_array($new_msg, $msg)) {
      drupal_set_message($new_msg);
    }
	}
}


function inserate_suchen_validate($form, &$form_state) {
	if (!$form_state['input']['search_api_views_fulltext'] || !$form_state['input']['address']) {
    $msg = drupal_get_messages('status');
    $new_msg = t('Bitte geben Sie sowohl einen Suchbegriff wie "Maler" oder "Maurer" und den Ort an welchem dieser benötigt ist ein.');

    if(!in_array($new_msg, $msg)) {
      drupal_set_message($new_msg);
    }
	}
}*/



function inserate_user_profile_validate($form, &$form_state) {

	if (!$form_state['input']['field_inserat_addresse'][LANGUAGE_NONE][0]['country']) {
		form_set_error('country', t('Das Feld "Land" ist erforderlich.'));
	}

	if(!$form_state['input']['field_inserat_addresse'][LANGUAGE_NONE][0]['locality']) {
		form_set_error('', t('Das Feld "Ort" ist erforderlich.'));
	}

  // DK: only do validation, when postal code is present as field
  if(isset($form['field_inserat_addresse']['und'][0]['locality_block']['postal_code'])) {
    if(!$form_state['input']['field_inserat_addresse'][LANGUAGE_NONE][0]['postal_code']) {
      form_set_error('', t('Das Feld "PLZ" ist erforderlich.'));
    }
  }
}


function inserate_validate($node, $form, &$form_state) {
}

function inserate_commerce_node_checkout_line_item_alter(&$line_item, $product, $node) {
#	dpm($line_item);
#	dpm($product);
#	dpm($node);
	global $user;

	// Rebuild Token Package Node

	$product_id=$line_item->commerce_product[LANGUAGE_NONE][0]['product_id'];

	$anzahl_tokens=0;
	$abo=$product->field_abo[LANGUAGE_NONE][0]['value'];

	$anzahl_tokens=$product->field_anzahl_tokens[LANGUAGE_NONE][0]['value'];

	$node->field_abo[LANGUAGE_NONE]=array(
		array(
			'value'=>$abo
		)
	);
	$node->field_anzahl_tokens[LANGUAGE_NONE]=array(
		array(
			'value'=>$anzahl_tokens
		)
	);


	$node->title=$product->title; //.' | '.$user->name.' | '.date('Y-m-d H:i:s');
#    dpm($product);
#    if($product->product_id==1)  $node->title=t('Das Kleine (5 Kontakte)');
#    if($product->product_id==2)  $node->title=t('Das Mittlere (10 Kontakte)');
#    if($product->product_id==3)  $node->title=t('Das Große (15 Kontakte)');

	$node->field_tokens_uebrig[LANGUAGE_NONE][0]['value']= $anzahl_tokens;
	$node->field_tokens_verbraucht[LANGUAGE_NONE][0]['value']= 0;
	$node->field_user_reference[LANGUAGE_NONE][0]['uid']=$node->uid;
	$node->field_product_id[LANGUAGE_NONE][0]['value']= $product_id;


	if(!$abo){
    if(in_array($product->product_id, array(1,2,3))) {
      $startdate = $node->field_startdatum[LANGUAGE_NONE][0]['value'];
      $timestamp = strtotime($startdate);

      $node->field_ablaufdatum[LANGUAGE_NONE][0]['value']=date("Y-m-d H:i:s", strtotime("+". $product->product_id ." month", $timestamp));
    } else {
      $node->field_ablaufdatum[LANGUAGE_NONE]=array();
      $node->field_startdatum[LANGUAGE_NONE]=array();
    }
	} else {
		$startdate=$node->field_startdatum[LANGUAGE_NONE][0]['value'];
		$timestamp=strtotime($startdate);
		$ablaufdatum=date("Y-m-d H:i:s", strtotime("+1 month", $timestamp));
		$node->field_ablaufdatum[LANGUAGE_NONE][0]['value']=$ablaufdatum;
	}
	node_save($node);
}

function inserate_cancel_ajax($arg1, $arg2, $arg3 ) {
  $form = drupal_get_form('inserate_cancel_form');
  print drupal_render($form);
}

function redeem_token_ajax($arg1, $arg2, $arg3) {
  $form = drupal_get_form('redeem_token_form', $arg1, $arg2, $arg3);
  print drupal_render($form);
}

function redeem_token_form($form, &$form_state, $arg1, $arg2, $arg3) {
	$form['token_paket_nid'] = array(
    '#type' => 'hidden',
    '#title' => 'Token Paket NID',
    '#default_value' => check_plain($arg1),
  );

	$form['target_uid'] = array(
    '#type' => 'hidden',
    '#title' => 'Target UID',
    '#default_value' => check_plain($arg2),
  );

	$form['branche_nid'] = array(
    '#type' => 'hidden',
    '#title' => 'Branche NID',
    '#default_value' => check_plain($arg3),
  );

  $cancel_link = 'node/' . check_plain($arg3);

  return confirm_form($form, t('Redeem token?'), $cancel_link, t('Redeem token'),t('Redeem token?'));
}

function redeem_token_form_submit($form, $form_state) {

	$oldest_package =	$form_state['input']['token_paket_nid'];
	$target_uid =		$form_state['input']['target_uid'];
	$branche_nid =		$form_state['input']['branche_nid'];


	inserate_redeem_token($oldest_package, NULL, NULL, $target_uid);
#	drupal_set_message(t('Token has been redeemed.'.' '.l('Zurück zum Inserat.', 'node/'.$inserat_nid) ), 'status');
	drupal_goto('node/'.$branche_nid);

}


function inserate_cancel_form($form_state) {

	$nid=check_plain(arg(1));
	$node=node_load($nid);
	$cancel_url='';

	switch ($node->type) {
		case 'application':
			$title=t('Cancel application');
			$text=t('Cancel application');
			$back_to=t('Cancel');
			$cancel_url='meine-anfragen/aktiv';
			break;
		case 'inserat':
			$title=t('Cancel ad');
			$text=t('Cancel ad');
			$back_to=t('Back');
			$cancel_url='node/'.$nid;
			break;
		case 'token_paket':
			$title=t('Cancel Token Package');
			$text=t('Ich möchte mein Token-Abo zum nächstmöglichen Termin kündigen? <br /><i>Anmerkung: Bitte beachten Sie, dass Ihr Abonnement bis zum ende der vereinbarten Laufzeit gültig ist und Sie bis dahin alle Vorzüge Ihres Abonnements nutzen können.</i>');
			$cancel_url='node/add/token-paket';
			$back_to=t('Back');
			break;
	}

	$form['nid'] = array(
    '#type' => 'hidden',
    '#title' => $title,
    '#default_value' => $nid,
    );


  	return confirm_form(
  		$form,
    	$title.'?',
        //'node/'.$nid,
       	$cancel_url,
        '<strong>'.$text.'</strong><br />'.
#        '<div class="helptext">'.t('This action cannot be undone.').'</div>',
        '',
        $title,
        $back_to

    );

}

function _inserate_validate_cancel_paypal($form, &$form_state) {
	global $user;


	if($form_state['input']['commerce_node_checkout_product']==5) {
		$abo_status=_inserate_abo_status();
		$product_id=$abo_status[0]->field_field_product_id[0]['raw']['value'];

		if($product_id==4) {
			// Cancel Standard Abo

			if(!$form_state['input']['checkbox_confirm_cancellation']) {
				form_set_error('checkbox_confirm_cancellation', t('Sie müssen der Kündigung Ihres Standard-Kontos zustimmen um ein Upgrade auf ein Premium-Konto durchführen zu können.'));
				return;
			}


			$result=commerce_pr_cancel_callback($user);
			if($result == 'success' ){

				// Cancel Drupal Package
				$cancellation_date=date('Y-m-d H:i:s');
				$nid=$abo_status[0]->nid;

				$node=node_load($nid);

				$node->field_cancelled[LANGUAGE_NONE][0]['value']=$cancellation_date;
				$node->field_status[LANGUAGE_NONE][0]['value']=1; // Zurückgezogen durch User

				node_save($node);
				drupal_set_message($message);
			} else {
#				dpm($result);
				form_set_error('', t('Your Paypal subscription could not be cancelled.'));
			}
		}
	}
}



function inserate_cancel_form_submit($form, $form_state) {
	global $user;

	$cancellation_date=date('Y-m-d H:i:s');
	$nid=$form_state['values']['nid'];
	$node=node_load($nid);
	if($node->uid <> $user->uid) {
		return MENU_ACCESS_DENIED ;
	}
	switch ($node->type) {
		case 'application':
			$message=t('Application cancelled');
			$goto='node/'.$nid;
			break;
		case 'inserat':
			$message=t('Ad cancelled');
			$goto='node/'.$nid;
			break;
		case 'token_paket':
			$message=t('Token package cancelled');
			$goto='node/add/token-paket';

			break;
	}

	// cancel paypal subscription
	if($node->type=='token_paket') {
		if($node->field_abo[LANGUAGE_NONE][0]['value']) {
			$result=commerce_pr_cancel_callback($user);
#          if(function_exists('_branche_expire_unpublish_branches'))  _branche_expire_unpublish_branches($user);
		}
	}



	// cancel connected applications
	if($node->type=='inserat') {

		$view=views_get_view('bewerbungen');
		$view->set_arguments(array($nid));
		$view->execute();
		foreach($view->result as $result) {
			$application=node_load($result->nid);
			$application->field_cancelled[LANGUAGE_NONE][0]['value']=$cancellation_date;
			$application->field_status[LANGUAGE_NONE][0]['value']=2; // Zurückgezogen durch Inserent
			node_save($application);

			// Send email notifications to applicants....

		}
	}


	$node->field_cancelled[LANGUAGE_NONE][0]['value']=$cancellation_date;
	$node->field_status[LANGUAGE_NONE][0]['value']=1; // Zurückgezogen durch User

	node_save($node);
	drupal_set_message($message);
	drupal_goto($goto);

}

function inserate_upgrade_form_submit($form, $form_state) {
	global $user;

	$cancellation_date=date('Y-m-d H:i:s');
	$nid=$form_state['values']['nid'];
	$node=node_load($nid);
	if($node->uid <> $user->uid) {
		return MENU_ACCESS_DENIED ;
	}
	$message=t('Token package upgraded');
	$goto='node/add/token-paket';

	// cancel paypal subscription
	if($node->field_abo[LANGUAGE_NONE][0]['value']) {
		$result=commerce_pr_cancel_callback($user);
	}

	$node->field_cancelled[LANGUAGE_NONE][0]['value']=$cancellation_date;
	$node->field_status[LANGUAGE_NONE][0]['value']=1; // Zurückgezogen durch User

#	node_save($node);
	drupal_set_message($message);

	commerce_cart_product_add_by_id($product_id, $quantity = 1, $combine = TRUE, $uid = NULL);

	drupal_goto($goto);

}

function _inserate_application_add_form() {
	global $user;

	module_load_include('inc', 'node', 'node.pages');

	$application_node = (object) array(
		'uid' => $user->uid,
		'name' => (isset($user->name) ? $user->name : ''),
		'type' => 'application',
		'language' => LANGUAGE_NONE
	);

	$form = drupal_get_form('application_node_form', $application_node);
	return drupal_render($form);
}

function _inserate_view_field_application($application_nid=NULL, $inserat_nid=NULL, $user_uid=NULL, $row) {

	// void function - not needed anymore
	// but still called from a view!

	return NULL;


}
function _inserate_token_exists($uid1, $uid2) {
	global $user;

	$sql="
		SELECT A.entity_id
			FROM
		{field_data_field_user_ref_init} A
			LEFT JOIN
		{field_data_field_user_ref_target} B using (entity_id)
			WHERE
		(
			A.field_user_ref_init_target_id = :uid1
				AND
			B.field_user_ref_target_target_id = :uid2
		) OR (
			A.field_user_ref_init_target_id = :uid2
				AND
			B.field_user_ref_target_target_id = :uid1
		)
		";

		$result=db_query($sql, array(':uid1'=>$uid1, ':uid2'=>$uid2));
		$record = $result->fetchObject();
		return $record;
}


function _inserate_get_oldest_token () {

	global $user;

	$view=views_get_view('oldest_token_package');
	$view->set_display('page_1'); // Abo
	$view->set_arguments(array($user->uid));
	$view->execute();

	if(!empty($view->result) && $view->result[0]->nid)	{
		// If valid Abo
		return $view->result[0]->nid;
	}

	$view=views_get_view('oldest_token_package');
	$view->set_display('page'); // Einzeltokens
	$view->set_arguments(array($user->uid));
	$view->execute();
	if(!empty($view->result) && $view->result[0]->nid)	{
		return $view->result[0]->nid;
	}
}

function _inserate_abo_status($uid=NULL) {

	if(!$uid) {
		global $user;
		$uid=$user->uid;
	}
	$view=views_get_view('meine_token_pakete');
	$view->set_arguments(array($uid));
	$view->set_display(array('page_2'));
	$view->execute();
	return($view->result);
}





function _inserate_abo_id($uid=NULL) {
	// Show original amount of tokens of the user's current abo package

	if(!$uid) {
		global $user;
		$uid=$user->uid;
	}
	$view=views_get_view('meine_token_pakete');
	$view->set_arguments(array($uid));
	$view->set_display(array('page_3'));
	$view->execute();

	$result=$view->result;

  if(isset($result[0])) {
    return $result[0]->field_field_anzahl_tokens[0]['raw']['value'];
  }

  return 0;
}




function _inserate_newsletter($arg) {
/**
	$content='Tcha - and here we actually need to embed a view ... its kinda dirty but wtf. Clean way is: https://drupal.org/node/1078116#comment-4239914';
**/

	$content='';

	$view = views_get_view('inserate_newsletter_mails' , TRUE);
	$view->set_arguments(array($arg));
	$view->set_display(array('block_1'));

	$view->execute();
	$output = $view->render();

	$content.= $output;


/**
This is more for my own info so I dont forget what to do next:
Clone this rule
Schedule one to run everyday (Rules scheduler) - add a filter in the VIEW VBO for the Bebachrichtung setting IS DAYLY

Clone the display of the view - filter - change filter on WEEKLY
Use that one for the weekly scheduled rule.

Would be better if we do the scheduling for early morning.
**/
	return $content;
}

function _identity_checked_status($uid) {
	$profile2=profile2_load_by_user(user_load($uid), $type_name = 'intern');
	$output="";
	$output.='<label class="hidden views-label views-label-identity-checked">'.t('Identity checked').': </label>';

	if ($profile2 && $profile2->field_identity_checked[LANGUAGE_NONE][0]['value'] ) {
		$output.='<img class="diy-icon field-identity-checked" src="/'.path_to_theme().'/ws-img/field_identity_checked-ja.png" alt="Identität überprüft: ja" title="Identität überprüft: ja"/>';
	}
	else {
		$output.='<img class="diy-icon field-identity-checked" src="/'.path_to_theme().'/ws-img/field_identity_checked-nein.png" alt="Identität überprüft: nein" title="Identität überprüft: nein"/>';

	}
	return $output;
}


function label_icon_content($field) {

  if(is_string($field)) {


// field_eigenes_transportmittel-ja.png

		if (stristr($field, 'Werkzeug')) {
			$fieldname='Eigenes Werkzeug';
			if(stristr($field, 'ja')) $filename='field_eigenes_werkzeug-ja';
			else $filename='field_eigenes_werkzeug-nein';
		}
		if (stristr($field, 'Transportmittel')) {
			$fieldname='Eigenes Transportmittel';
			if(stristr($field, 'ja')) $filename='field_eigenes_transportmittel-ja';
			else $filename='field_eigenes_transportmittel-nein';
		}
		if (stristr($field, 'Stundenlohn')) {
			$fieldname='Stundenlohn';
			$filename='field_stundenlohn';
			$tagged_content='<span>'.str_replace('Stundenlohn:', '', $field).'</span>';
		}

		$content=strip_tags($field);

    if(!isset($tagged_content)) {
      $tagged_content='<span class="hidden">'.strtolower($content).'</span>';
    }

	} else {
		$fieldname=$field->handler->field;
		$content=strip_tags($field->content);
		if(in_array(strtolower($content), array('ja','nein') ) ){
			$filename=$fieldname.'-'.strtolower($content);
			$tagged_content='<span class="hidden">'.strtolower($content).'</span>';
		} else {
			$filename=$fieldname;
			$tagged_content='<span>'.$content.'</span>';
		}
	}


	$field_label = '';
  if(isset($field->label)) {
    $field_label = $field->label;
  }

	$output="";
	$output.='<label class="hidden views-label views-label-'.$fieldname.'">'.$field_label.': </label>';
	$output.='<img class="diy-icon '.$fieldname.'" src="/'.path_to_theme().'/ws-img/'.$filename.'.png" alt="'.$field_label.'" title="'.$field_label.'"/>';
	$output.=$tagged_content;

	return $output;
}


function _inserate_lineitem() {

	$line_item=commerce_line_item_load(21);
	$node_checkout_node_nid=$line_item->commerce_node_checkout_node[LANGUAGE_NONE][0]['nid'];
	#dpm($line_item);
	return NULL;

}

function _meinkonto_benachrichtigungen() {
	/*
	if($form_id == 'profile2_edit_notifications_form') {
		$form['profile_notifications']['field_expiry_inserat'][LANGUAGE_NONE]['#title']='';
		$form['profile_notifications']['field_ich_m_chte_ber_neuen_bewer'][LANGUAGE_NONE]['#title']='';
	}
	if($form_id == 'profile2_edit_benachrichtigungen_anfragen_form') {
	*/

	global $user;

	$profile2=profile2_load_by_user($user, $type_name = 'notifications');
	$output='';
	$form=drupal_get_form('profile2_edit_notifications_form');
	#dpm( drupal_render($form));
	return drupal_render($form) ;
}


function _inserate_user_has_valid_branchenprofil() {

	// Visibility of Application Form in Inserate Panel
	global $user;
	$sql="
	SELECT
	A.nid
	FROM
	{node} A

	WHERE
	A.type='branche'
	AND
	A.uid=:uid
	";


	$result=db_query($sql, array(':uid'=>$user->uid));
	$record = $result->fetchObject();
	if($record) {
		return TRUE;
	}

	return FALSE;
}

/**
 * Implements HOOK_cron();
 */
function inserate_cron() {
  // get last run time
  $last_run = variable_get('inserate_cron_last_run', 0);
  $last_run_plus_one_day = $last_run + (24 * 60 * 60);

  // cron has never run OR
  // last run is 24 hours behind
  if($last_run_plus_one_day < time()) {
    // get all users to check
    _inserate_check_outdated_users();
    _inserate_check_outdated_inserations();
    // Set current run time
    variable_set('inserate_cron_last_run', time());
  }
}

/**
 * Checking outdated inserations
 */
function _inserate_check_outdated_inserations() {
  watchdog('inserate', 'Checking for outdated inserations');

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'inserat')
    ->propertyCondition('status', 1)
    ->propertyCondition('created', strtotime('-50 days'), '<')
    ->fieldCondition('field_status', 'value', '0')
    ->addMetaData('account', user_load(1));

  $result = $query->execute();
  if (isset($result['node'])) {
    $inseration_nids = array_keys($result['node']);
    $inserations = entity_load('node', $inseration_nids);

    foreach($inserations as $inseration) {
      _inserate_check_outdated_applications($inseration);

      $wrapper = entity_metadata_wrapper('node', $inseration);
      $wrapper->field_status->set(3);
      $wrapper->save();
      watchdog('inserate', 'Set inseration @inseration (@nid) to outdated', array('@inseration' => $inseration->title, '@nid' => $inseration->nid));
    }
  }

  return '';
}

/**
 * Checks for outdated application based upon inserations
 */
function _inserate_check_outdated_applications($inseration) {
  watchdog('inserate', 'Checking outdated applications for @inseration (@nid)', array('@inseration' => $inseration->title, '@nid' => $inseration->nid));

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'application')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_status', 'value', '0')
    ->fieldCondition('field_inserat_referenz', 'target_id', $inseration->nid)
    ->addMetaData('account', user_load(1));

  $result = $query->execute();
  if (isset($result['node'])) {
    $application_nids = array_keys($result['node']);
    $applications = entity_load('node', $application_nids);

    foreach($applications as $application) {
      $wrapper = entity_metadata_wrapper('node', $application);
      $wrapper->field_status->set(3);
      $wrapper->save();
      watchdog('inserate', 'Set application @application (@nid) to outdated', array('@application' => $application->title, '@nid' => $application->nid));
    }
  }
}

/**
 * Helper function for quering active inserations between given date
 */
function inserate_get_inserate_between($from, $to) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'inserat')
    ->propertyCondition('status', 1)
    ->propertyCondition('created', array($from, $to), 'BETWEEN')
    ->fieldCondition('field_status', 'value', '0')
    ->addMetaData('account', user_load(1));

  $result = $query->execute();
  if (isset($result['node'])) {
    $news_items_nids = array_keys($result['node']);
    $news_items = entity_load('node', $news_items_nids);

    return $news_items;
  }

  return FALSE;
}

function _inserate_check_outdated_users() {
  if($users_to_check = _inserate_get_outdated_users_to_check()) {
    foreach($users_to_check as $uid) {
      $max_branche = _inserate_get_allowed_branches($uid);

      _inserate_limit_branches($uid, $max_branche);
    }
  }

  return '';
}

function _inserate_get_allowed_branches($uid = NULL) {
  if(!$uid) {
    global $user;
    $uid = $user->uid;
  }

  // per default
  $max_branche = 1;

  // get all not-outdated abos
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'token_paket')
    ->propertyCondition('uid', $uid) // node written by a specific user
    ->propertyCondition('status', 1) // published nodes
    ->fieldCondition('field_abo', 'value', 1, '=')
    ->fieldCondition('field_ablaufdatum', 'value', date("Y-m-d H:i:s"), '>=')
    ->addMetaData('account', user_load(1)); // Run the query as user 1.

  $result = $query->execute();
  if (isset($result['node'])) {
    $existing_abos = array_keys($result['node']);

    foreach($existing_abos as $abo_nid) {
      $abo = node_load($abo_nid);

      if($product_field = field_get_items('node', $abo, 'field_product_id')) {
        if($product = commerce_product_load($product_field[0]['value'])) {
          if($branchen_field = field_get_items('commerce_product', $product, 'field_max_brancheneintragungen')) {
            $max_branche = max($max_branche, $branchen_field[0]['value']);

            #dpm('STEP 3 - Bestehende Abos: User: ' . $uid . ', Abo: ' . $abo_nid . ', Max Branchen: ' . $max_branche);
          }
        }
      }
    }
  }

  return $max_branche;
}

function _inserate_limit_branches($uid, $count) {
  #dpm('STEP 4 - Limitieren: User: ' . $uid . ', Max Branchen: ' . $count);

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'branche')
    ->propertyCondition('uid', $uid) // node written by a specific user
    ->propertyCondition('status', 1) // published nodes
    ->fieldCondition('field_profil_verbergen', 'value', 2, '=') // "Nicht verbergen"
    ->addMetaData('account', user_load(1)) // Run the query as user 1.
    ->propertyOrderBy('created', 'ASC')
    ->range($count, PHP_INT_MAX);

  $result = $query->execute();
  if (isset($result['node'])) {
    $branches_hide = array_keys($result['node']);

    // hide all branches here
    foreach($branches_hide as $branche_nid) {
      $branche = node_load($branche_nid);

      $wrapper = entity_metadata_wrapper('node', $branche);
      $wrapper->field_profil_verbergen->set(1);
      $wrapper->save();

      #dpm('STEP 5 - Verstecken: ' . $uid . ', Branche: ' . $branche_nid);
    }
  }
}

/**
 * Helper function to get users with outdated abos
 */
function _inserate_get_outdated_users_to_check() {
  if($outdated_abos = _inserate_get_outdated_abos()) {
    $users_to_check = array();
    foreach($outdated_abos as $abo) {
      $abo_node = node_load($abo);
      $users_to_check[] = $abo_node->uid;
    }
    #dpm('STEP 2 - User zum prüfen: ' . implode(',', $users_to_check));
    return array_unique($users_to_check);
  }

  return;
}

/**
 * Helper function to get outdated abos
 */
function _inserate_get_outdated_abos() {
  // we need profiles, with at least one existent abo, which has expired

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'token_paket')
    ->fieldCondition('field_abo', 'value', 1, '=')
    ->fieldCondition('field_ablaufdatum', 'value', date("Y-m-d H:i:s"), '<')
    ->addMetaData('account', user_load(1)); // Run the query as user 1.

  $result = $query->execute();
  if (isset($result['node'])) {
    $outdated_abos = array_keys($result['node']);
    #dpm('STEP 1 - Abgelaufene Abos: ' . implode(',', $outdated_abos));
    return $outdated_abos;
  }

  return;
}

/**
 * Implements HOOK_node_validate().
 */
function inserate_node_validate($node, $form, &$form_state) {
  global $user;
  if(!in_array('administrator', $user->roles) && $node->type == 'branche') {

    // Check if current node is going to be visible
    if($field_branche_hide = field_get_items('node', $node, 'field_profil_verbergen')) {
      if($field_branche_hide[0]['value'] == 2) {

        // user is allowed to list X branches
        $max_branche = _inserate_get_allowed_branches();

        // returns all visible branches
        if($visible_branche = _inserate_get_visible_branches()) {
          // but the current edited node can also be visible
          $visible_branche = array_combine($visible_branche, $visible_branche);
          if(isset($visible_branche[$node->nid])) {
            unset($visible_branche[$node->nid]);
          }

          #dpm('Allowed branches: ' . $max_branche. ', Current active branches (without THIS one): '. count($visible_branche));
          if(count($visible_branche) >= $max_branche) {
            form_set_error('field_profil_verbergen');
            drupal_set_message('Dein derzeitiges Abonnement erlaubt keine weiteren Branchenprofile. Um weitere Branchenprofile anzulegen / aktiviere bitte ein neues Abo-Paket.');
          }
        }
      }
    }
  }
}

function _inserate_application_done_already($nid, $uid) {
  $sql="
	SELECT
	A.field_inserat_referenz_target_id, B.uid, B.nid
	FROM
	{field_data_field_inserat_referenz} A
	LEFT JOIN
	{node} B
	ON A.entity_id = B.nid

	WHERE
	A.bundle='application'
	AND
	A.field_inserat_referenz_target_id=:inserat_nid
	AND
	B.uid=:uid
	";


  $result=db_query($sql, array(':inserat_nid' => $nid, ':uid' => $uid));
  $record = $result->fetchObject();
  if($record) {
    return true;
  }

  return false;
}

/**
 * Returns all visible branches for one user
 */
function _inserate_get_visible_branches($uid = NULL) {
  if(!$uid) {
    global $user;
    $uid = $user->uid;
  }

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'branche')
    ->propertyCondition('uid', $uid) // node written by a specific user
    ->propertyCondition('status', 1) // published nodes
    ->fieldCondition('field_profil_verbergen', 'value', 2, '=') // "Nicht verbergen"
    ->addMetaData('account', user_load(1)); // Run the query as user 1.

  $result = $query->execute();
  if (isset($result['node'])) {
    $active_branches = array_keys($result['node']);
    return $active_branches;
  }

  return array();
}

/**
 * Implements HOOK_node_presave().
 */
function inserate_node_presave($node) {
  if(in_array($node->type, array('branche', 'inserat')) && $node->is_new) {
    if(isset($node->domains_raw) && !empty($node->domains_raw)) {
      $first_domain = reset($node->domains_raw);
      $node->domain_source = $first_domain;
    }
  }
}


// we can delete this afterwards
function _inserate_display_bewerben_link() {

}