/**
 * Webnews (www.webnews.de) comments syndication - comments form script.
 * @version $Id: comments_form.js 883 2008-08-01 16:21:14Z ahofmann $
 */
WN_comments_form = {
	/**
	 * @param {Hash} Languages
	 */
	lang : {
		'de': {
          	},
		'de-inform': {
			'Schreiben Sie Ihren Kommentar (<span id="WN_commLength">0</span>/<span>%length</span> Zeichen)':
				'Schreib deinen Kommentar (<span id="WN_commLength">0</span>/<span>%length</span> Zeichen)',
			'Ihr Name': 'Dein Name',
			'Ihr Kommentar': 'Dein Kommentar'
		}
	},

	/**
	 * @param {String} Story url
	 */
	url : '',

	/**
	 * @param {String} Api key
	 */
	apikey : '',

	/**
	 * @param {Bool} Story exists
	 */
	storyExists : false,

	/**
	 * @param {String} Username on webnews
	 */
	username : '',

	/**
	 * @param {Int} Max comment length
	 */
	maxCommentLength : 0,

	/**
	 * @param {String} Header text
	 */
	header : '',

	/**
	 * @param {Bool} E-mail notifications enabled
	 */
	emailNotifyActive : '',

	/**
	 * @param {String} E-mail notifications help text
	 */
	emailNotifyHelp : '',

	/**
	 * @param {String} Captcha code key
	 */
	captchaKey : '',

	/**
	 * @param {Bool} E-mail notifications allowed
	 */
	notifications : false,

	/**
	 * Translate a string
	 * @param s The string to translate
	 * @param args An object of replacement pairs to apply after translation.
	 */
    t: function(s, args) {
		str = this.language[s];
		if (typeof str == 'undefined') {
			str = s;
		}
		if (args) {
			for (var key in args) {
				str = str.replace(key, args[key]);
			}
		}
		return str;
	},

	/**
	 * Running script method
	 */
	run : function() {
		// prepare translation via this.t()
		if (typeof WN_Lang != 'undefined' && typeof this.lang[WN_Lang] != 'undefined') {
			this.language = this.lang[WN_Lang];
                }
		else {
			this.language = this.lang['de'];
		}

		this.url = document.location;
		if (typeof WN_Story != 'undefined' && WN_Story != '') {
			this.url = WN_Story;
		}

		if (typeof WN_ApiKey != 'undefined' && WN_ApiKey != '') {
			this.apikey = WN_ApiKey;
		}

		if (typeof WN_comments_list != 'undefined') {
			WN_comments_list.generateOutput(true);
		}

		if (typeof WN_Notifications != 'undefined') {
			this.notifications = WN_Notifications;
		}

		this.checkStory();
	},

	/**
	 * Check story (call to remote server)
	 */
	checkStory : function() {
		document.write('<scr'+'ipt src="http://tools.webnews.de/api_cs/check?&apikey=' + this.apikey + '&url=' + this.urlencode(this.url) + '"></scr'+'ipt>');
	},

	/**
	 * checkStory() method callback
	 *
	 * @param {Object} json JSON data
	 * @see #makeCall
	 */
	checkStoryCallback : function(json) {
		if (json.url == this.url) {
			this.storyExists 		= json.exists;
			this.maxCommentLength	= json.max_length;
			this.header				= json.header;
			this.emailNotifyActive	= json.email_notify_active;
			this.emailNotifyHelp	= json.email_notify_help;
			this.captchaKey			= json.captchaKey;

			if (json.exists) {
				this.showForm(json.username);
			} else {
				this.postUrl();
			}
		}
	},

	/**
	 * Method shows comment form
	 *
	 * @param {String} username Webnews logged in username
	 */
	showForm : function(username) {

		this.username = username;

		formAttributesFields = '';
		if (typeof WN_fields == 'object' && WN_fields.length > 0) {
			for (i=0; i<WN_fields.length; i++) {
				if (i > 9) {
					break;
				}
				formAttributesFields += this.createFormAttribute(WN_fields[i]);
			}
		}

		document.write(
			'<a name="WN_form"></a>' +
			'<form id="WN_commForm" action="http://tools.webnews.de/api_cs/comment?&apikey=' + this.apikey + '&url=' + this.urlencode(this.url) + '" method="post" onsubmit="return WN_comments_form.checkForm(this)">' +
			'<input type="hidden" name="parentComment" id="parentComment" value="0"/>' +
			'<input type="hidden" name="ref" value="' + document.location + '"/>' +
			'<h4>' +
			(this.header != '' ? this.header : this.t('Kommentar')) +
			'</h4><a href="http://www.webnews.de" class="WN_wnbanner"><img src="http://comments.webnews.de/style/wnbanner.gif" alt="wnbanner" border="0"/></a>' +
			'<div class="WN_topbar">' + this.t('Schreiben Sie Ihren Kommentar (<span id="WN_commLength">0</span>/<span>%length</span> Zeichen)', { '%length': this.maxCommentLength }) + '</div>' +
			(typeof WN_Topbar_subtitle != 'undefined' ?  '<p class="WN_topbar_extra">' + WN_Topbar_subtitle + '</p>' : '' ) +
			'<div class="WN_error" id="WN_error"></div>' +
			formAttributesFields +
			'<div class="WN_answer" id="WN_answer"></div>' +
			'<div class="WN_frame">');

		if (username) {
			document.write('<div class="WN_form-item"><span class="WN_label WN_author">' + this.t('Ihr Name') + ': ' +
					'<span class="WN_username"><span>' + username + '</span> ' + this.t('bei webnews.de') + '</span></span></div>' +
				'<input type="hidden" name="author" value="' + username + '" />');
		} else {
			document.write('<div class="WN_form-item"><span class="WN_label author">' + this.t('Ihr Name') + ':</span> ' +
				'<input type="text" name="author" class="WN_author" maxlength="15" /></div>');
		}

		document.write(
			'<div class="WN_form-item"><span class="WN_label WN_comment">' + this.t('Ihr Kommentar') + ':</span> <textarea name="comment" rows="5" cols="20" class="WN_comment" onkeyup="WN_comments_form.commLength(this)"></textarea></div>' +
			'<div class="WN_captcha"><img src="http://tools.webnews.de/captcha.png?key=' + this.captchaKey + '" alt="" /></div>' +
			'<input type="hidden" name="captchaKey" value="' + this.captchaKey + '" />' +
			'<div class="WN_form-item"><span class="WN_label captcha">' + this.t('Captcha') + ':</span> <input type="text" name="captcha" maxlength="6" class="WN_captcha" /></div>');

		if (!username) {
			if (this.emailNotifyActive && this.notifications) {
				document.write(
					'<input type="checkbox" name="email_notify_chbox" id="WN_email_notify_chbox" value="Yes" onblur="WN_comments_form.showEmailField(this.checked);" onclick="WN_comments_form.showEmailField(this.checked);" /> ' +
					this.emailNotifyHelp +
					'<div id="WN_email_notify_address" style="display:none;">' +
					'E-Mail-Adresse:<br/><input type="text" name="email_notify_address" value="' + this.getEmailCookie() + '" />' +
					'</div>'
				);
			}
		}

		document.write(
			'<div><input type="submit" value="' + this.t('Abschicken') + '" class="WN_submit" id="WN_submit" /></div>' +
			'</div>' +
			'</form>');

		document.write('<scr'+'ipt type="" src="http://tools.webnews.de/api_cs/messages?&apikey=' + this.apikey + '&url=' + this.urlencode(this.url) + '"></scr'+'ipt>');
	},

	/**
	 * Messages callback
	 * @param {Object} json JSON with messages array
	 */
	messages : function(json) {

		message = '';
		for (i=0; i<json.messages.length; i++) {
			message += json.messages[i]+'<br/>\n';
		}

		if (message.length > 0) {
			document.getElementById('WN_error').innerHTML = message;
		}

		// reload form data
		if (typeof json.formdata.author != 'undefined') {
			fObj = document.getElementById('WN_commForm');
			fObj.parentComment.value	= json.formdata.parentComment;
			if (this.username == '' || this.username == null) {
				fObj.author.value		= json.formdata.author;
			}
			fObj.comment.value			= json.formdata.comment;
		}
	},

	/**
	 * Method used to set parent comment id
	 * @param {Int} id Parent comment id
	 */
	setParentComment : function(id, username, timeago) {
		document.getElementById('parentComment').value = id;

		li = document.getElementById('WN_comments').childNodes;
		for (i=0; i<li.length; i++) {
			li[i].className = '';
		}
		document.getElementById('WN_comm'+id).className = 'selected';

		// Antworten auf Kommentar von gman.php vor 9 Minuten
		document.getElementById('WN_answer').innerHTML = this.t('Antworten auf Kommentar von %user %timeago', { '%user': username, '%timeago': timeago});
	},

	/**
	 * Method used to validade comment form
	 *
	 * @param {Object} fObj Form object
	 * @return {Bool} Form is validated information
	 */
	checkForm : function(fObj) {

		document.getElementById('WN_error').innerHTML = '';

		if (this.trim(fObj.author.value) == '' || fObj.captcha.value.length < 2) {
			document.getElementById('WN_error').innerHTML = this.t('Der Autor darf nicht leer sein.');
			return false;
		}

		if (this.trim(fObj.comment.value) == '' || fObj.captcha.value.length < 2) {
			document.getElementById('WN_error').innerHTML = this.t('Der Kommentar darf nicht leer sein.');
			return false;
		}

		if (this.trim(fObj.captcha.value) == '' || fObj.captcha.value.length < 6) {
			document.getElementById('WN_error').innerHTML = this.t('Captcha ist falsch.');
			return false;
		}

		if (document.getElementById('WN_email_notify_chbox').checked) {
			emailAddress = fObj.email_notify_address.value;
			if (!this.validateEmail(emailAddress)) {
				document.getElementById('WN_error').innerHTML = this.t('Dies ist keine gültige E-Mail-Adresse. Bitte prüfen Sie die Eingabe.');
				this.setEmailCookie(emailAddress, false);
				return false;
			}
			this.setEmailCookie(emailAddress, true);
		}

		return true;
	},

	/**
	 * Autoposting URL if not exists in database.
	 */
	postUrl : function() {

		cat		= 0;
		desc	= '';
		local	= '';

		metaTags = document.getElementsByTagName('meta');
		for (i=0; i<metaTags.length; i++) {
			switch (new String(metaTags[i].name).toLowerCase()) {
				case 'dc.category':
					cat = metaTags[i].content;
					break;

				case 'description':
					desc = metaTags[i].content;
					break;

				case 'geo.placename':
					local = metaTags[i].content;
					break;
			}
		}

		// description (WN_Description paremeter)
		if (typeof WN_Description != 'undefined' && WN_Description != '') {
			desc = WN_Description;
		}

		// page title (WN_Title paremeter)
		title = document.title;
		if (typeof WN_Title != 'undefined' && WN_Title != '') {
			title = WN_Title;
		}

        catMap = {
            11: 13, // Politik
            48: 49, // Wirtschaft-Finanzen
            1: 6, // Technologie
            37: 69, // Unterhaltung
            55: 56, // Lifestyle
            24: 31, // Sport
            32: 36, // Wissenschaft
            43: 44 // Spiele
        }
		if (cat > 0 && typeof catMap[cat] != 'undefined') {
			cat = catMap[cat];
		}

		document.write(
			'<form id="WN_postForm" action="http://tools.webnews.de/api_cs/post?&apikey=' + this.apikey + '&url=' + this.urlencode(this.url) + '" method="post">' +
			'<input type="hidden" name="ref" value="' + document.location + '"/>' +
			'<input type="hidden" name="cat" value="' + cat + '"/>' +
			'<input type="hidden" name="title" value="' + this.urlencode(title) + '"/>' +
			'<input type="hidden" name="desc" value="' + this.urlencode(desc) + '"/>' +
			'<input type="hidden" name="local" value="' + this.urlencode(local) + '"/>' +
			'</form>');
		setTimeout(function() {
			document.getElementById('WN_postForm').submit();
		}, 1);
	},

	/**
	 * Trim string method
	 * @param {String} str Input string
	 * @return {String} Stripped whitespace string
	 */
	trim : function(str) {
		return str.replace(/^\s+|\s+$/, '');
	},

	/**
	 * Urlencode method
	 *
	 * @param {String} str String to encode
	 * @return {String} Encoded string
	 * @link http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_urlencode/
	 * @author Philip Peterson
	 * @author Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	 */
	urlencode : function(str) {

	    var ret = str;

	    ret = ret.toString();
	    ret = encodeURIComponent(ret);
	    ret = ret.replace(/%20/g, '+');

	    return ret;
	},

	/**
	 * Checks comment length and updates HTML code (n/500 Zeichen)
	 *
	 * @param {Object} Textarea object
	 */
	commLength : function(elemObj) {
		if (elemObj.value.length > this.maxCommentLength) {
			elemObj.value = elemObj.value.substring(0, this.maxCommentLength);
		}
		document.getElementById('WN_commLength').innerHTML = elemObj.value.length;
	},

	/**
	 * Creates single form attribute entry
	 *
	 * @param {Object} attrObj
	 * @return {String} HTML attribute code
	 */
	createFormAttribute: function(attrObj) {

		// validate type
		if (typeof attrObj.type == 'undefined') {
			attrObj.type = 'text';
		}
		// check correct type
		switch (attrObj.type) {
			case 'text':
			case 'checkbox':
				break;
			default:
				attrObj.type = 'text';
		}
		// validate name
		if (typeof attrObj.name != 'string') {
			return;
		}
		// check description
		if (typeof attrObj.description != 'string') {
			attrObj.description = '';
		}
		// check label
		if (typeof attrObj.label != 'string') {
			attrObj.label = '';
		}

		attrObj.name = 'attr_'+attrObj.name;

		// HTML output
		htmlOutput = '';
		if (attrObj.label != '') {
			htmlOutput = '<label for="' + attrObj.name + '">' + attrObj.label + '</label>';
		}

		if (attrObj.type == 'checkbox') {
			htmlOutput += '<input type="' + attrObj.type + '" name="' + attrObj.name + '" value="Yes" />';
			htmlOutput += '<input type="hidden" name="' + attrObj.name + '_chbox" value="No" />';
		} else {
			htmlOutput += '<input type="' + attrObj.type + '" name="' + attrObj.name + '"/>';
		}

		if (attrObj.description != '') {
			htmlOutput += '<div class="descrition">' + attrObj.description + '</div>';
		}

		return htmlOutput;
	},

	/**
	 * Shows e-mail address input field if checkbox was choosed
	 *
	 * @param {Bool} state
	 */
	showEmailField: function(state) {
		document.getElementById('WN_email_notify_address').style.display = (state ? 'block' : 'none');
	},

	/**
	 * Validate e-mail address. Uses modified Matt's code found at http://www.designplace.org/scripts.php?page=1&c_id=22
	 *
	 * @param {String} E-mail address
	 * @link http://www.designplace.org/scripts.php?page=1&c_id=22
	 * @return {Bool} True if e-mail address was valid or not given; other cases false.
	 */
	validateEmail: function(email) {

		if (this.trim(email) != '') {
            validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;

            if (email.search(validRegExp) == -1) {
                return false;
            }
		}
        return true;
	},

	/**
	 * Remember e-mail address for future cases
	 *
	 * @param {String} email
	 * @param {Bool} state
	 */
	setEmailCookie: function(email, state) {

		_expires = new Date();
		if (state) {
			_expires.setDate(_expires.getDate()+7);
		} else {
			_expires.setDate(_expires.getDate()-1);
		}

		_cookie = 'preEmailAddress=' + email + '; expires='+_expires.toGMTString()+'; path=/';
		document.cookie = _cookie;
	},

	/**
	 * Gets e-mail address from cookie
	 *
	 * @see WN_comments_form.setEmailCookie()
	 * @return {String} Cookie stored e-mail address or empty string.
	 */
	getEmailCookie: function() {
		preEmailAddress = document.cookie.match(/preEmailAddress=([^;]+)/);
		if (preEmailAddress != null && typeof preEmailAddress[1] != 'undefined') {
			return preEmailAddress[1];
		}
		return '';
	}
}

/* Running script */
WN_comments_form.run();
