/**
 * cordite.js - functionality for cordite CMS
 *
 */

YUI().use('node', function (Y) {

	// function to open external links in new window/tab
	var externalLink = function (e) {
		e.target.set('target', '_blank');
	};
	
	var initPage = function (e) {
		// create external links
		Y.all('a.external').on('click', externalLink);
	}
	
	// page load listener
	Y.on('domready', initPage);
});

// cordite cms tag preview highlighting
YUI().use('node', function(Y) {

	var highlightTags = function (e) {
		
		// strings
		var elements = Y.all('.cordite_cms_string_tag').each(function () {
			
			console.log('processing strings...');
			console.log(this.get('tagName') + ':' + this.get('id'));
			
			var parent = this.get('parentNode');
			parent.addClass('cordite-cms-string-tag');
			obj = Y.Node.create('<div>&nbsp;</div>');
			Y.one(document.body).append(obj);
			obj.addClass('cordite-cms-string-tag-tab');
			obj.setX(getPageOffsetLeft(parent));
			obj.setY(getPageOffsetTop(parent) - 10);
			
		});
		
		// regions
		var elements = Y.all('.cordite_cms_region_tag').each(function () {
			
			console.log('processing regions...');
			console.log(this.get('tagName') + ':' + this.get('id'));
			
			this.addClass('cordite-cms-region-tag');
			obj = Y.Node.create('<div>&nbsp;</div>');
			Y.one(document.body).append(obj);
			obj.addClass('cordite-cms-region-tag-tab');
			obj.setX(getPageOffsetLeft(this));
			obj.setY(getPageOffsetTop(this) - 10);
			
		});
		
		// images
		var elements = Y.all('.cordite_cms_image_tag').each(function () {
			console.log('processing images...');
			console.log(this.get('tagName') + ':' + this.get('id'));
			img = this.get('firstChild');
			console.log(img.get('tagName') + ':' + img.get('id'));
			
			
			boundary = Y.Node.create('<div></div>');
			boundary.addClass('cordite-cms-image');
			boundary.setX(getPageOffsetLeft(img));
			boundary.setY(getPageOffsetTop(img));
			boundary.setStyle('width', parseInt(img.getStyle('width')) - 4);
			boundary.setStyle('height', parseInt(img.getStyle('height')) - 4);
			Y.one(document.body).append(boundary);
			
			tab = Y.Node.create('<div>&nbsp;</div>');
			Y.one(document.body).append(tab);
			tab.addClass('cordite-cms-image-tag-tab');
			tab.setX(getPageOffsetLeft(img));
			tab.setY(getPageOffsetTop(img) - 10);
			
		});
	};
	
	Y.on('domready', highlightTags);
	
	var getPageOffsetLeft = function(o) {
		var x;
		x = o.get('offsetLeft');
		if (o.get('offsetParent') !=  null)
			x += getPageOffsetLeft(o.get('offsetParent'));
		return x;
	};
	
	var getPageOffsetTop = function(o) {
		var y;
		y = o.get('offsetTop');
		if (o.get('offsetParent') !=  null)
			y += getPageOffsetTop(o.get('offsetParent'));
		return y;
	};
});
