/**
 * Copyright 2010 Sven Johansson (johansson.sven@gmail.com)
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

$(document).ready(
	function() {
		addEditIconsToLinks();
	}
);

function addEditIconsToLinks() {
	addEditIcons('.plinkitem',
		onEditIconClickPageLink
	);
}

function onEditIconClickPageLink() {
	var pageId = getCurrentPageId();
	var linkPath = calculateItemPath(this.id);
	var resourceUrl = '_madmin/pages/'+ pageId + '/' + linkPath;
 
	openEditor(
		function() {
			$.get(
				resourceUrl,
				function(responseData) {
					showForm(
						'Edit link',
						getPageLinkFormObject(responseData),
						function() {
							var formData = collectPageLinkForm();
							var formJson = '{ "linkKey" : "' + formData.linkKey + '", "linkText" : "' + formData.linkText + '", "targetPage" : "' + formData.targetPage + '"}';
							
							$.ajax({
								type: 'PUT',
								url: resourceUrl,
								data: formJson,
								success: function() {
									applyPageLinkChanges(formJson);
								},
								contentType: 'application/json'
							});
						}
					);
				},
				'application/json'
			);
		}
	);
	
}

function collectPageLinkForm() {
	var formData = {
		'linkKey' : $('#ff-linkKey').val(),
		'linkText': $('#ff-linkText').val(),
		'targetPage' : $('#ff-targetPage').val()
	};
	
	return formData;
}

function applyPageLinkChanges(linkJsonString) {
	reloadPage();
}

function getPageLinkFormObject(linkJsonString) {
	
	var linkJson = eval('(' + linkJsonString + ')');
	
	var formSpec = {
		'width'  : 500,
		'height' : 200,
		'fields' : [
		    { 'fieldName' : 'linkKey',
		      'value' : linkJson.linkKey,
		      'type' : 'hidden'
		    },
		    { 'label' : 'Text',
		      'fieldName' : 'linkText',
		      'value' : linkJson.linkText,
		      'type' : 'text',
		      'width' : 65
		    },
		    { 'label' : 'Target Page',
		      'fieldName' : 'targetPage',
		      'value' : linkJson.targetPage,
		      'type' : 'text',
		      'width' : 15
		    }
	    ]
	};

	return formSpec;
}

