/**
  * Saves a new node.
  */
 public function actionSaveNewNode()
 {
     $this->requirePostRequest();
     $this->requireAjaxRequest();
     // New NodeModel
     $node = new AmNav_NodeModel();
     $returnData = array('success' => false, 'message' => Craft::t('Not all required fields are filled out.'));
     // Set attributes
     $attributes = craft()->request->getPost();
     if (!empty($attributes['navId']) && !empty($attributes['name'])) {
         // Make sure we save a valid URL, if set
         if (isset($attributes['url'])) {
             $url = $attributes['url'];
             if (substr($url, 0, 3) == 'www') {
                 $url = 'http://' . $url;
             }
             $node->setAttribute('url', $url);
         }
         // Is there an element ID available?
         if (isset($attributes['elementId'])) {
             $node->setAttribute('elementId', $attributes['elementId']);
             $node->setAttribute('elementType', $attributes['elementType']);
         }
         $node->setAttributes(array('navId' => $attributes['navId'], 'parentId' => (int) $attributes['parentId'], 'name' => $attributes['name'], 'blank' => isset($attributes['blank']) ? $attributes['blank'] == 'true' : false, 'enabled' => true, 'locale' => $attributes['locale']));
         // Save the node!
         if (($node = craft()->amNav_node->saveNode($node)) !== false) {
             // Get element URL if required
             if ($node->elementId) {
                 switch ($node->elementType) {
                     case ElementType::Entry:
                         $entry = craft()->entries->getEntryById($node->elementId, $node->locale);
                         if ($entry) {
                             $node->url = $entry->uri == '__home__' ? '{siteUrl}' : '{siteUrl}' . $entry->uri;
                         }
                         break;
                     case ElementType::Category:
                         $category = craft()->categories->getCategoryById($node->elementId, $node->locale);
                         if ($category) {
                             $node->url = '{siteUrl}' . $category->uri;
                         }
                         break;
                 }
             }
             // Return data
             $returnData['success'] = true;
             $returnData['message'] = Craft::t('Node added.');
             $returnData['nodeData'] = $node;
             // Get parent options
             $navigation = craft()->amNav->getNavigationById($node->navId);
             $nodes = craft()->amNav->getNodesByNavigationId($node->navId, $attributes['locale']);
             $variables['selected'] = $node->parentId;
             $variables['parentOptions'] = craft()->amNav->getParentOptions($nodes, $navigation->settings['maxLevels'] ?: false);
             $returnData['parentOptions'] = $this->renderTemplate('amNav/_build/parent', $variables, true);
         }
     }
     // Return result
     $this->returnJson($returnData);
 }