<?php

// Parse the parameters from the Ajax.Request

//if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER ['HTTP_X_REQUESTED_WITH']  == 'XMLHttpRequest') {
	require( dirname(__FILE__) . '/../../../../wp-config.php' );
	if (!(is_user_logged_in() && current_user_can('edit_posts')))
		die("Athentication failed!");

	
	global $wpdb, $canvas;
	$parent = $_GET['parent'];
	$template_name = $_GET['template_name'];
	$template_size = $_GET['template_size'];
	$listitems = array();

	$wpdb->query("UPDATE ".$canvas->main." 
			SET 	template_name='$template_name',
				template_size='$template_size'
			WHERE block_id='$parent'");

	// Save the new values to the database
	foreach ($_GET as $key => $value) {
		$key = trim(urldecode($key));
		$value = trim(urldecode($value));

		if (($key != "_")&&($key != "parent")&&($key != "checked")) {
			if(strstr($key, 'canvaslist')) {
				$key = preg_replace('/^([0-9]*)canvaslist_/','',$key);
				if(!in_array($key, $listitems)) $listitems[] = $key;
				$$key .= $value."|";
				continue;
			}
			if($var_id = $wpdb->get_var("SELECT variable_id FROM ".$canvas->variables." WHERE variable_name = '$key' AND parent='$parent'")) {
				$wpdb->query("UPDATE ".$canvas->variables." SET value='$value' WHERE variable_name='$key' AND parent='$parent'");	 
				$updated_vars[] = $var_id;
			}
		}
	}

	// Handle list items
	if($listitems) {
		foreach($listitems as $item) {
			$new_value = preg_replace('/(\|*)$/', '', $$item);
			$wpdb->query("UPDATE ".$canvas->variables." SET value='$new_value' WHERE variable_name='$item' AND parent='$parent'");
		}
	}

	// Save any values that weren't passed in the GET string, eg. empty checkboxes
	$variables = $wpdb->get_results("SELECT variable_id,type FROM ".$canvas->variables." WHERE parent='$parent' AND variable_id NOT IN ('".implode("','", $updated_vars)."')");
	
	if (!empty($variables)) {
		foreach ($variables as $variable) {
			// Here's where we define what the default "false" value is for each variable type
			switch ($variable->type) {
				case "Boolean":
					$wpdb->query("UPDATE ".$canvas->variables." SET value='0' WHERE variable_id='$variable->variable_id'");
				break;
			}
		}
	}
//}
?>