/* ripped straight from MT */

function zeropad(num) {
	return (num < 10) ? '0' + num : num;
}
function old_update_authored_on() {
	var now = new Date();
	var y = now.getFullYear();
	var m = zeropad(now.getMonth() + 1);
	var d = zeropad(now.getDate());
	var h = zeropad(now.getHours());
	var min = zeropad(now.getMinutes());
	var s = zeropad(now.getSeconds());
	return y + '-' + m + '-' + d + ' ' + h + ':' + min + ':' + s;;
}

function update_authored_on()
{
	$( 'timeUpdating' ).innerHTML = 'Downloading the current time from server...';
	$( 'timeUpdating' ).style.color = 'gray';
	$( 'timeUpdateRow' ).style.display = '';
	new Ajax.Request( '/ged/?op=timewrapper', { 'onComplete' : time_updated } );
}

function time_updated( resp )
{
	var issuedSet = false;
	var fromEditor = false;
	var server = '';
	if( resp != null )
	{
		var text = resp.responseText;
		var parts = text.split( /;/ );
		if( parts.length > 1 )
		{
			if( parts.length > 2 && parts[2] == 'fixed' )
			{
				fromEditor = true;
			}
			if( /^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}$/.match( parts[1] ) )
			{
				$('issued').value = parts[1];
				server = parts[0];
				issuedSet = true;
			}
		}
	}
	var message = 'Synchronized to local time on ' + server;
	var color = 'gray';
	if( !issuedSet )
	{
		$( 'issued' ).value = old_update_authored_on();
	 	message = 'Synchronized to local time in browser';
	 	color = 'red';
	}
	else if( fromEditor ) color = 'black';
	$( 'timeUpdating' ).innerHTML = message;
	$( 'timeUpdating' ).style.color = color;
	setTimeout( function(){ $( 'timeUpdateRow' ).style.display = 'none'; }, 3000 );
}

var canFormat = 0;
if (document.selection)
    canFormat = 1;
var ua = navigator.userAgent;
if ( ( ua.indexOf('Gecko') >= 0 && ua.indexOf('Safari') < 0 ) || ua.indexOf( 'Chrome' ) != -1 )
    canFormat = 1;

function getSelected (e) {
    if (document.selection)
	{
        e.focus();
        var range = document.selection.createRange();
        return range.text;
    }
	else
	{
        var length = e.textLength;
		//if (length == undefined) return;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2) end = length;
        return e.value.substring(start, end);
    }
}

function setSelection (e, v) {
	var scrollTop = e.scrollTop;
    if (document.selection) {
        e.focus();
        var range = document.selection.createRange();
        range.text = v;
    } else {
        var length = e.textLength;
        var start = e.selectionStart;
        var end = e.selectionEnd;
        if (end == 1 || end == 2) end = length;
        e.value = e.value.substring(0, start) + v + e.value.substr(end, length);
        e.selectionStart = start + v.length;
        e.selectionEnd = start + v.length;
    }
    e.focus();
	e.scrollTop = scrollTop;
}


function formatStr (e, v) {
    if (!canFormat) return;
    var str = getSelected(e);
    if (!str) return;
    setSelection(e, '<' + v + '>' + str + '</' + v + '>');
    return false;
}

function insertLink (e, isMail) {
    if (!canFormat) return;
    var str = getSelected(e);
    var link = '';
    if (!isMail) {
        if (str.match(/^https?:/)) {
            link = str;
        } else if (str.match(/^(\w+\.)+\w{2,5}\/?/)) {
            link = 'http://' + str;
        } else if (str.match(/ /)) {
            link = 'http://';
        } else {
            link = 'http://' + str;
        }
    } else {
        if (str.match(/@/)) {
            link = str;
        }
    }
    var my_link = prompt(isMail ? trans('Enter email address:') : trans('Enter URL:'), link);
    if (my_link != null) {
         if (str == '') str = my_link;
         if (isMail) my_link = 'mailto:' + my_link;
        setSelection(e, '<a href="' + my_link + '">' + str + '</a>');
    }
    return false;
}

var Lexicon = {};


function trans(str) {
    if (Lexicon && Lexicon[str])
        str = Lexicon[str];
    if (arguments.length > 1)
        for (var i = 1; i <= arguments.length; i++) {
            str = str.replace(new RegExp('\\[_' + i + '\\]', 'g'), arguments[i]);
            var re = new RegExp('\\[quant,_' + i + ',(.+?)(?:,(.+?))?\\]');
            var matches;
            while (matches = str.match(re)) {
                if (arguments[i] > 1)
                    str = str.replace(re, arguments[i] + ' ' +
                        ((typeof(matches[2]) != 'undefined') > 2 ? matches[2]
                                                                 : matches[1]
                                                                   + 's'));
                else
                    str = str.replace(re, arguments[i] + ' ' + matches[1]);
            }
        }
    return str;
}

// some small changes from mt version for use with prototype
function swapTag(tag) {
	var kw = $('tags').value;
	if (!kw) kw = ' ';
	var tags = kw.match(/('[^']+?'|"[^"]+?"|[^ ;,]+)/g);
	var present = false;

	if (tags) {
		tags.each( function(r,i){
			this_tag = r.replace(/(^['"]|['"]$)/g, '');
			if (this_tag.toLowerCase() == tag.toLowerCase()) {
				tags.splice(i,1); 
				present = true;
			}
		});
	}

	if (tag.match(/\s/)) tag = '"' + tag + '"';

	if (tags) {
		if (!present) tags.push(tag);
		$('tags').value = tags.join(' ') + ' '; 
	} else {
		$('tags').value = tag + ' ';
	}

	$('tags').focus();
}



/* end MT ripoffs */

function toggleEditor(value) {
	if(value == 'visual') {
		tinyMCE.get('entry').show();
		$('toggleHTML').removeClassName('selected');
		$('toggleVisual').addClassName('selected');
	}
	else if (value == 'html') {
		tinyMCE.get('entry').hide();
		$('toggleVisual').removeClassName('selected');
		$('toggleHTML').addClassName('selected');
	}
	
	return false;
}

var originalEditorAction = '';
var previewNewWindow = false;

function toggleSubmit( value, url, newWindow )
{
	if( url == null ) url = '/';
	if( originalEditorAction != null && originalEditorAction != '' ) $('post_form').action = originalEditorAction;
	if( value == 'preview' )
	{
		$('previewPost').value = '1';
		previewNewWindow = ( newWindow ? true : false );
	}
	else if( value == 'save' )
	{
		$('previewPost').value = '0';
	}
	if( !checkPostData() ) return false;
	return postSave( url );
}

function postSave( url )
{
	if( url == null ) url = '/';
	$('responseFormat').value = 'ajax';
	$('savebutton').disable();
	$('savespinner').style.display='inline'; // can't just show, needs to remain inline
	var p = new Post( $('post_form' ) );
	p.save( url );
	return false;
}

var Post = function( postForm )
{
	this.postForm = postForm;
}

Post.prototype.save = function( url )
{
  	if( url == null ) url = '/';
	var obj = this;
	this.previewUrl = '';
	this.postId = 0;
	this.imageProcessCounter = 0;
	this.url = url;
	this.json = null;
	$( 'saveMessages' ).innerHTML = 'Saving post...';
	$( 'saveMessages' ).show();
	var options = {
		parameters: this.postForm.serialize(),
		method: 'post',
		onComplete: function(){ obj.onComplete(); },
		onFailure: function(){ obj.onFailure() },
		onSuccess: function(resp, json){ obj.onSuccess(resp, json); }
	};
	new Ajax.Request( url, options );
}

Post.prototype.onSuccess = function( resp, json )
{
			if (json == null || !json.postSave)
			{
				showError( 'Failed to save the post', 'Invalid response from the server, please try again later.' );
				return;
			}

			if( json.postSave.success != true )
			{
				showError( 'The post cannot be saved', this.parseKinjaError( json.postSave.message ) );
				return;
			}

		 	this.postId = json.postSave.postId;
			this.json = json;
			if( json.postSave.preview ) this.previewUrl = json.postSave.preview;
			if( json.postSave.needImageProcess ) this.processImages();
			else this.finishSave();
}

Post.prototype.parseKinjaError = function( msg )
{
	if( msg )
	{
		if( msg.indexOf( 'Invalid byte 3 of 3-byte UTF-8 sequence.' ) != -1 ) msg = 'There is at least one invalid character somewhere in the text';
		else if( msg.indexOf( 'Unable to add/modify post:' ) != -1 ) msg = msg.replace( /Kinja API error response: [a-z0-9]+ - Unable to add\/modify post: (.+)/, 'Some of the images on host $1 are not available' );
	}  
	return msg; 
}

Post.prototype.onFailure = function()
{
	showError( 'The server is unavailable', 'Please try again later.' );
}

Post.prototype.onComplete = function()
{
	/*
	even if a bad response (hence, oncomplete instead of on[Success|Failure])
	 - re-enable save button
	 - stop spinner
	*/
	$('savebutton').enable();
	$('savespinner').hide();
	
}

Post.prototype.processImages = function()
{
	$('savebutton').disable();
	$('savespinner').style.display='inline'; // can't just show, needs to remain inline
	this.imageProcessCounter++;
	$( 'saveMessages' ).innerHTML = '<div style="float: left;">Processing images...</div><div style="float: left; background-color: black; height: 5px; width: ' + ( this.imageProcessCounter * 10 ) + 'px; margin: 5px 0px 0px 10px;">&nbsp;</div><div style="clear: both;"></div>';
	
	var obj = this;
	var options = {
		parameters: { 'id' : this.postId, 'op' : 'admin_savepost_image', 'counter' : this.imageProcessCounter },
		method: 'post',
		onComplete: function( resp ) { obj.imagesProcessed( resp ); }
	};
	new Ajax.Request( this.url, options );
}

Post.prototype.imagesProcessed = function( resp )
{
	var data = null;
	try
	{
		data = eval( '(' + resp.responseText + ')' );
	}
	catch( ex )
	{
		showError( 'The server\'s response cannot be parsed', '' );
		this.finishSave();
		return;
	}
	if( data.nextRun )
	{
		var obj = this;
		setTimeout( function() { obj.processImages() }, 3000 );
	}
	else
	{
		if( !data.success ) showError( 'The images are still not processed', 'GED will save it again later' );
		this.finishSave();
	}
}

Post.prototype.finishSave = function()
{
	this.onComplete();
	$( 'saveMessages' ).innerHTML = 'Post saved';
	if( this.previewUrl )
	{
		$( 'saveMessages' ).innerHTML = '';
		$( 'saveMessages' ).hide();
		var trg = ( previewNewWindow ? '_blank' : 'previewPost' );
		window.open( this.json.postSave.preview, trg );
	}
	else
	{
		var newUrl = '/ged/' + this.postId + '?poststatus=saved';
		if( GanjaGears && GanjaGears.runningApp && GanjaGears.runningApp.postCode ) newUrl += '&postCode=' + encodeURIComponent( GanjaGears.runningApp.postCode ); 
		location = newUrl;
	}
}

function showError( errorMessage, errorReason )
{
	$( 'saveMessages' ).hide();
	if( !errorReason ) errorReason = '';
	$( 'errorMessage' ).innerHTML = '<b>' + errorMessage + '.</b> ' + errorReason ; 
	$( 'errorMessage' ).show();
	setTimeout( function() { $( 'errorMessage' ).hide() }, 60000 );
}

function flushCache( postId )
{
	if( cacheFlushing ) return false;
	if( postId == null || !postId || !parseInt( postId ) ) return false;
	cacheFlushing = true;
	var url = '/?op=admin_postcache_invalidate&postId=' + parseInt( postId );
	var options = {
		'onComplete' : function ( resp ) { flushCacheCompleted( resp ) }
	};
	new Ajax.Request( url, options );
	$('savespinner').style.display='inline';
}

function flushCacheCompleted( resp )
{
	cacheFlushing = false;
	$('savespinner').style.display='none';
	var message = 'Postcache is successfully flushed';
	if( resp == null || resp.responseText != 'OK' ) message = 'Please try again';
	$( 'cacheMessage' ).innerHTML = message; 
	$( 'cacheMessage' ).style.display = 'block';
	setTimeout( '$( \'cacheMessage\' ).style.display = \'none\'', 3000 );
}

cacheFlushing = false;

var typo = new Array();
var cname = 'spinner';
var cval = 'alt';
document.observe("dom:loaded", function() {
	document.observe('keypress', function(e) {
		var code;
		if (!e) var e = window.event;
		if (e.keyCode) code = e.keyCode;
		else if (e.which) code = e.which;

		ignore = /input|textarea/i;
		tag = (e.target || e.srcElement).tagName;
		if( ignore.test(tag)) return;

		var character = String.fromCharCode(code).toLowerCase();
		typo[typo.length] = character;
		str = printArray( typo );
		if( MD5(str) == 'e785058034d8d90712dae39fd34c52fc' )
		{
			Cookie.set(cname,cval, 14);
			location.reload(true);
		}
	});
	
	try
	{
		spin = Cookie.get(cname);
		if( Cookie.get(cname) == cval)
		{
			$('imgSpinnerSrc').writeAttribute("src", "http://publish.gawker.com/assets/ged/img/alt_spinner.gif");
		}
	}
	catch( err )
	{}
	
	setInterval('clearArray( typo );', 10000);
});


function printArray( arr )
{
	str = '';
	for (var index = 0, len = arr.length; index < len; ++index) {
		str+= arr[index];
	}
	return str;
}

function clearArray( arr )
{
	arr.clear();
}

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};


/**
*
*  MD5 (Message-Digest Algorithm)
*  http://www.webtoolkit.info/
*
**/

var MD5 = function (string) {

    function RotateLeft(lValue, iShiftBits) {
        return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
    }

    function AddUnsigned(lX,lY) {
        var lX4,lY4,lX8,lY8,lResult;
        lX8 = (lX & 0x80000000);
        lY8 = (lY & 0x80000000);
        lX4 = (lX & 0x40000000);
        lY4 = (lY & 0x40000000);
        lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
        if (lX4 & lY4) {
            return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
        }
        if (lX4 | lY4) {
            if (lResult & 0x40000000) {
                return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
            } else {
                return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
            }
        } else {
            return (lResult ^ lX8 ^ lY8);
        }
     }

     function F(x,y,z) { return (x & y) | ((~x) & z); }
     function G(x,y,z) { return (x & z) | (y & (~z)); }
     function H(x,y,z) { return (x ^ y ^ z); }
    function I(x,y,z) { return (y ^ (x | (~z))); }

    function FF(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function GG(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function HH(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function II(a,b,c,d,x,s,ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b);
    };

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1=lMessageLength + 8;
        var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
        var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
        var lWordArray=Array(lNumberOfWords-1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while ( lByteCount < lMessageLength ) {
            lWordCount = (lByteCount-(lByteCount % 4))/4;
            lBytePosition = (lByteCount % 4)*8;
            lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
            lByteCount++;
        }
        lWordCount = (lByteCount-(lByteCount % 4))/4;
        lBytePosition = (lByteCount % 4)*8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
        lWordArray[lNumberOfWords-2] = lMessageLength<<3;
        lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
        return lWordArray;
    };

    function WordToHex(lValue) {
        var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
        for (lCount = 0;lCount<=3;lCount++) {
            lByte = (lValue>>>(lCount*8)) & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
        }
        return WordToHexValue;
    };

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    };

    var x=Array();
    var k,AA,BB,CC,DD,a,b,c,d;
    var S11=7, S12=12, S13=17, S14=22;
    var S21=5, S22=9 , S23=14, S24=20;
    var S31=4, S32=11, S33=16, S34=23;
    var S41=6, S42=10, S43=15, S44=21;

    string = Utf8Encode(string);

    x = ConvertToWordArray(string);

    a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;

    for (k=0;k<x.length;k+=16) {
        AA=a; BB=b; CC=c; DD=d;
        a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
        d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
        c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
        b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
        a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
        d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
        c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
        b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
        a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
        d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
        c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
        b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
        a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
        d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
        c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
        b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
        a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
        d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
        c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
        b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
        a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
        d=GG(d,a,b,c,x[k+10],S22,0x2441453);
        c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
        b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
        a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
        d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
        c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
        b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
        a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
        d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
        c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
        b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
        a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
        d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
        c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
        b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
        a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
        d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
        c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
        b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
        a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
        d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
        c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
        b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
        a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
        d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
        c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
        b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
        a=II(a,b,c,d,x[k+0], S41,0xF4292244);
        d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
        c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
        b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
        a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
        d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
        c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
        b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
        a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
        d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
        c=II(c,d,a,b,x[k+6], S43,0xA3014314);
        b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
        a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
        d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
        c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
        b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
        a=AddUnsigned(a,AA);
        b=AddUnsigned(b,BB);
        c=AddUnsigned(c,CC);
        d=AddUnsigned(d,DD);
    }

    var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);

    return temp.toLowerCase();
}

function togglePostParameters( show )
{
	if( show == null )
	{
		if( $( 'postParametersContainer' ).style.display == 'none' ) show = true;
		else show = false;
	}
	var text = 'Show post parameters &darr;';
	var display = 'none';
	if( show )
	{
			text = 'Hide post parameters &uarr;';
			$( 'gearsBox' ).show();
			$( 'postParametersContainer' ).show();
			//$( 'postParametersTopContainer' ).show();
	}
	else
	{
			$( 'gearsBox' ).hide();
			$( 'postParametersContainer' ).hide();
			//$( 'postParametersTopContainer' ).hide();
	}
	$( 'postParametersControl' ).innerHTML = text;
	return false;
}

Shortcuts = function( data )
{
	var obj = this;
	Event.observe( window, 'load', function( e ) { obj.init( data ) } );
}

Shortcuts.prototype.init = function( data )
{
	var parsedData = {};
	for( var i = 0; i < data.length; i++  )
	{
		parsedData[data[i].code] = data[i].handler;
	}
	this.data = parsedData;
	var obj = this;
	Event.observe( window, 'keydown', function( e ) { obj.handle( e ) } )
}

Shortcuts.prototype.handle = function( e )
{
	var code = '';
	if( e.shiftKey ) code += 's';
	if( e.ctrlKey ) code += 'c';
	if( e.altKey ) code += 'a';
	if( e.metaKey ) code += 'm';
	code += String.fromCharCode( e.keyCode );
	code = code.toLowerCase();
	if( this.data[code] ) this.data[code](); 
}

var GEDShortcuts = [
	{
		'code' : 'ap',
		'handler' : function() { $( 'previewbutton' ).click(); }
	},
	{
		'code' : 'as',
		'handler' : function() { $( 'savebutton' ).click(); }
	}
];

function checkPostData()
{
	var errors = [];
	if( !$( 'issued' ).value.match( /^[0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}$/ ) ) errors.push( 'Please check the timestamp format (2008-12-01 10:40:34) and try again.' );
	if( !$( 'entry' ).value.length ) errors.push( 'Check your entry and try publishing again' );
//	if( !$( 'title' ).value.length ) errors.push( 'Check your title and try publishing again' );
	if( errors.length )
	{
		showError( 'There are problems that need to be fixed before saving', '<br />' + errors.join( '<br />' ) );
		return false;
	}
	return true;
}

PostParamsConfig = function( toShow )
{
	if( !toShow ) toShow = false;
	else toShow = true;
	this.toShow = toShow;
	var cookieList = document.cookie.split( '; ' );
	this.cookies = {};
	for( var i = 0; i < cookieList.length; i++ )
	{
		var cookieParts = cookieList[i].split( '=' );
		this.cookies[cookieParts[0]] = cookieParts[1];
	}
	this.postParamsEnabled = toShow ? 1 : 0;
	if( this.cookies['postParamsEnabled'] == 1 ) this.postParamsEnabled = 1;
	var obj = this;
	var clickLink = function( e )
	{
		obj.togglePostParamsBox();
		return false;
	};
	$( 'postParamsLink' ).observe( 'click', clickLink );
	this.setPostParams();
}

PostParamsConfig.prototype.savePostParams = function()
{
	var date = new Date();
	date.setTime( date.getTime + 30 * 38400 * 1000 );
	document.cookie = 'postParamsEnabled=' + this.postParamsEnabled + '; expires=' + date.toGMTString() + '; path=/';
}

PostParamsConfig.prototype.togglePostParamsBox = function()
{
	this.postParamsEnabled = 1 - parseInt( this.postParamsEnabled );
	this.setPostParams();
}

PostParamsConfig.prototype.setPostParams = function()
{
	$( 'postParamsLink' ).innerHTML = 'Parameter box is ' + ( this.postParamsEnabled ? 'ON' : 'OFF' );
	var enable = this.postParamsEnabled;
	if( this.toShow )
	{
		enable = true;
		this.toShow = false;
	}
	togglePostParameters( enable ); 
	this.savePostParams();	
}

PostParamsConfig.synchronizeSettings = function( fromId, toId )
{
	if( $( fromId ).type == 'checkbox' ) $( toId ).checked = $( fromId ).checked;
	else if( $( fromId ).type == 'select' ) $( toId ).selectedIndex = $( fromId ).selectedIndex;
	else $( toId ).value = $( fromId ).value; 
}
