/**
 * Javascript file
 *
 * @package    Content Templater editor button
 * @version    1.1.4a
 * @since      File available since Release 1.0.0
 *
 * @author     Peter van Westen <peter@nonumber.nl>
 * @link       http://www.nonumber.nl/contenttemplater
 * @copyright  Copyright (C) 2009 NoNumber! All Rights Reserved
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

var CT_f = {
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",


	getXML : function( id, editorname )
	{
		CT_f._startLoad();
		var myXHR = new XHR( {
				method: 'get',
				onSuccess: function( data ) { CT_f._insertTexts( data, editorname ); },
				onFailure: function() { CT_f._finishLoad(); }
			} );
		myXHR.send( CT_root+'index.php?option=com_contenttemplater&id='+id );
	},

	_insertTexts : function( data, editorname )
	{
		var data = data;
		data = CT_f._decode( data );
		data = data.split( '[/CT]' );

		var params = new Object;
		for ( i = 0; i < data.length; i++ )
		{
			if ( data[i].indexOf('[CT]' ) != -1 ) {
				vals = data[i].split( '[CT]' );
				key = ckey = vals[1].trim();
				params[ key ] = new Object;
				params[ key ]['default'] = vals[2].trim();
				params[ key ]['value'] = vals[3].trim();
			}
		}

		var has_content = 0;

		for ( key in params )
		{
			param = params[key];
			if ( key == 'content' && param['value'].length ) {
				has_content = 1;
			} else {
				if ( param['value'] != param['default'] ) {
					field_val = CT_f._getValue( key );
					if ( field_val != param['value'] ) {
						CT_f._setValue( key, param['value'] );
						if ( key == 'sectionid' && document.adminForm && document.adminForm.sectionid && sectioncategories ) {
							changeDynaList( 'catid', sectioncategories, document.adminForm.sectionid.options[document.adminForm.sectionid.selectedIndex].value, 0, 0);
						}
					}
				}
			}
		}

		if ( has_content ) {
			for ( key in params )
			{
				param = params[key];

				if ( key == 'content' && param['value'].length ) {
					if ( param['value'].length ) {
						CT_f._jInsertEditorText( param['value'], editorname );
					}
				}
			}
		} else {
			CT_f._finishLoad();
		}
	},

	_jInsertEditorText : function( value, editor, count )
	{
		var count = ( count == null ) ? 1 : ++count;
		if ( count < 10 ) {
			try {
				jInsertEditorText( value, editor );
				succes = 1;
			}
			catch(err) {
				window.setTimeout ( function() {
					CT_f._jInsertEditorText( value, editor, count )
				}, 500 );
				succes = 0;
			}
			if ( succes ) {
				document.getElementById(editor).value += value;
				CT_f._finishLoad();
			}
		} else {
			alert( 'Could not find the editor!' );
			CT_f._finishLoad();
		}
	},

	_getClient : function()
	{
		var ua = navigator.userAgent.toLowerCase();
		var client = {
			isStrict: document.compatMode == "CSS1Compat",
			isOpera: ua.indexOf("opera") > -1,
			isIE: ua.indexOf("msie") > -1,
			isIE7: ua.indexOf("msie 7") > -1,
			isSafari: /webkit|khtml/.test(ua),
			isWindows: ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1,
			isMac: ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1,
			isLinux: ua.indexOf("linux") != -1
		};
		return client;
	},

	_getDocHeight : function()
	{
		var client = CT_f._getClient();
		var h = window.innerHeight;
		var mode = document.compatMode;
		if ((mode || client.isIE) && !client.isOpera) {
			h = client.isStrict ? document.documentElement.clientHeight: document.body.clientHeight
		}
		return h;
	},

	_fixTop : function()
	{
		this.overlay.style.top = document.documentElement.scrollTop + 'px';
	},

	_startLoad : function()
	{
		var client = CT_f._getClient();

		this.overlay = new Element( 'div', {
			id: 'CT_f._overlayz',
			styles: {
				cursor: 'wait',
				background: 'black url('+CT_root+'/plugins/editors-xtd/contenttemplater/images/loading.gif) no-repeat center center',
				position: 'fixed',
				left: 0,
				top: 0,
				width: '100%',
				height: '100%',
				zIndex: 5000
			}
		} ).addEvent( 'click', function(){ CT_f._finishLoad(); } );

		if ( client.isIE && !client.isIE7 ) {
			this.overlay.style.position = 'absolute';
			this.overlay.style.height = CT_f._getDocHeight() + 'px';
			CT_f._fixTop();
			window.addEvent( 'scroll', function(){ CT_f._fixTop(); } );
		}

		this.fx = {
			fade: this.overlay.effect( 'opacity', {
				duration: 250,
				wait: false}).set(0)
		};
		$(document.body).adopt( this.overlay );
		this.fx.fade.start(0.7);

	},

	_finishLoad : function()
	{
		this.fx.fade.start(0);
	},

	_getValue : function( key )
	{
		element = document.getElementById( key );
		if( !element ) {
			element = document.adminForm.elements[ key ];
		}
		if( !element ) {
			return "";
		}
		var elementLength = element.length;
		if( element.type == 'select-one' || !elementLength ) {
			return element.value;
		} else {
			for(var i = 0; i < elementLength; i++) {
				if( element[i].checked ) {
					return element[i].value;
				}
			}
		}
		return "";
	},

	_setValue : function( key, value )
	{
		element = document.getElementById( key );
		if( !element ) {
			element = document.adminForm.elements[ key ];
		}

		if( !element ) {
			// Try frontend field names
			key = CT_f._getFrontendKey( key );
			element = document.getElementById( key );
			if( !element ) {
				element = document.adminForm.elements[ key ];
			}
		}

		if( !element ) {
			return;
		}

		var elementLength = element.length;
		if( !elementLength ) {
			element.value = value.toString();
			return;
		} else {
			values = value.split(',');
			var valuesLength = values.length;
			for(var i = 0; i < elementLength; i++) {
				element[i].checked = false;
				element[i].selected = false;
				for(var j = 0; j < valuesLength; j++) {
					if( element[i].value == values[j].toString() ) {
						element[i].checked = true;
						element[i].selected = true;
					}
				}
			}
			return;
		}
	},

	_getFrontendKey : function( key )
	{
		if ( key == 'metadescription' )
			return 'metadesc';
		if ( key == 'metakeywords' )
			return 'metakey';
		return key.replace('details','');
	},

	_decode : function( input )
	{
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = CT_f._utf8_decode(output);

		return output;
	},

	_utf8_decode : function( utftext )
	{
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}

		return string;
	}
}