var COMMUNITYCOOKIE_NAME = "idgc_saved_posting";
var COMMUNITYCOOKIE_MINUTES_ALIVE = 15;
var QUERYSTRING_VARNAME_POSTOK = "postOk";

var COMMUNITYPOSTING_BODY_PREFIX = "commentBody_";
var COMMUNITYPOSTING_BODYEDIT_PREFIX = "commentBodyEditForm_";

var ERROR_POST_FAILED = "Ett problem verkar ha uppst\u00E5tt, formul\u00E4ret du skickade kommer att \u00E5terskapas. Var god f\u00F6rs\u00F6k igen.";
var ERROR_FORM_NOT_FOUND = "Formul\u00E4ret som skulle \u00E5terskapas kunde inte hittas p\u00E5 sidan, kanske beh\u00F6ver du logga in igen?";
var COOKIE_RESTORE_FAILED = "Det gick inte att l\u00E4sa cookien med sparad kommentars-redigering, det verkar fattas information.";
var COOKIE_CONFIRM_DELETION = "Klicka OK om du vill beh\u00E5lla informationen.\nV\u00E4lj avbryt om du vill ta bort cookien.";
var COOKIE_COOKIE_NOERROR = "Du har en cookie med en sparad kommentars-redigering, men det hittades inget fel i samband med denna.";


/** Action for reporting a post */
function report(formId) {
	var theForm = document.getElementById(formId);
	setLocalAction(theForm);
	theForm.articleRenderMode.value = "report";
	theForm.submit();
}

/** Action for replying to a post */
function reply(formId) {
	var theForm = document.getElementById(formId);
	setLocalAction(theForm);
	theForm.articleRenderMode.value = "reply";
	theForm.submit();
}

/** Action for watching a post's replies */
function watch(formId) {
    var theForm = document.getElementById(formId);
    setPostAction(theForm);
    theForm.actionMode.value = "action_watch";
    theForm.submit();
}

/** Action for stopping watching a post's replies */
function watchEnd(formId) {
    var theForm = document.getElementById(formId);
    setPostAction(theForm);
    theForm.actionMode.value = "action_watch_end";
    theForm.submit();
}

/** Action for editing a post */
function edit(formId) {
	var theForm = document.getElementById(formId);
	setPostAction(theForm);
	theForm.actionMode.value = "action_edit";
	theForm.submit();
}

/** Simple toggle-function for displaying/hiding a post's editform */
function toggleEditForm(postingId) {
	var currentDisplay = getBodyEditFormDiv(postingId).style.display;
	if(currentDisplay == 'none') {
		showEditForm(postingId);
	}else{
		hideEditForm(postingId);
	}
}

/** Hides a post's body-part and displays the edit-form */
function showEditForm(postingId) {
	getBodyContentDiv(postingId).style.display='none';
	getBodyEditFormDiv(postingId).style.display='block';
}

/** Hides a post's edit-form and displays the body-part */
function hideEditForm(postingId) {
	getBodyContentDiv(postingId).style.display='block';
	getBodyEditFormDiv(postingId).style.display='none';
}

/** Gets the div-object containing a certain post body. */
function getBodyContentDiv(postingId) {
	return document.getElementById(COMMUNITYPOSTING_BODY_PREFIX + postingId);
}

/** Gets the div-object containing a certain post's edit-form. */
function getBodyEditFormDiv(postingId) {
	return document.getElementById(COMMUNITYPOSTING_BODYEDIT_PREFIX + postingId);
}

/** Sets the form to a get-action, to a jsp form page */
function setLocalAction(theForm) {
	theForm.action = "";
	theForm.method = "get";
}
  
/** Sets the form to a direct post-action */
function setPostAction(theForm) {
	theForm.action = "/jsp/createPosting.jsp";
	theForm.method = "post";
}



/**
 * Disables the enter-key in selected form elements.
 * This is needed for multi-purpose forms, who has 
 * to be submitted through a button.
 */
function disableEnterKey(event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		return false;
	}else{
		return true;
	}
}

/**
 * Checks if the user has a cookie with saved
 * values for a specific form
 *
 * @param
 *		A form object 
 *
 * @return true if the cookie was found
 */
function formHasStoredData(postForm) {
	var formString = readCommunityCookie(FIELDNAME_FORM);
	return (formString != null && formString != "");
}

/**
 * Creates and sets a cookie
 * 
 * @param name
 *			the cookie name
 * @param value 
 *			the cookie value string
 * @param
 *			the expire time in minutes 
 */
function setCommunityCookie(name, value, minutes) {
	if (minutes) {
		var date = new Date();
		date.setTime(date.getTime()+(minutes*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+ escape(value) +expires+"; path=/";
}

/**
 * Attempts to get a users cookie with the specified name.
 * A null-object is returned if it was not found.
 */
function getCommunityCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
			var result = c.substring(nameEQ.length,c.length);
			return unescape(result);
		}
	}
	return null;
}

/**
 * Empties the value of the cookie and makes it expire.
 */
function deleteCommunityCookie(name) {
	setCommunityCookie(name, "", -1);
}

/**
 * Checks if the user has a saved community postings-cookie.
 * If one is found, we delete it if its msg was just posted.
 * Or, if a problem was found we restore the form an notify
 * the user of this.
 */
function checkCommunityCookies() {
	var cookieValue = getCommunityCookie(COMMUNITYCOOKIE_NAME);
	if(cookieValue != null) {
		// a cookie was found, check post status
		var postOk = getQueryVariable(QUERYSTRING_VARNAME_POSTOK);
		
		// There was a post, and all went good - remove the cookie
		if(postOk != null && postOk == "true") {
			deleteCommunityCookie(COMMUNITYCOOKIE_NAME);
		}else if(postOk == "false") {
			alert(ERROR_POST_FAILED);
			restoreFormFromCookie(cookieValue);
		}else{
			// Msg about saved cookie, but no error found?
			if(confirm(COOKIE_COOKIE_NOERROR + "\n\n" + COOKIE_CONFIRM_DELETION)) {
				restoreFormFromCookie(cookieValue);
			}else{
				deleteCommunityCookie(COMMUNITYCOOKIE_NAME);
			}
		}
		
		
	}
}

/**
 * Tries to restore a form from the value submitted.
 * The string sent as argument should represent the
 * same mapping as CommunityObject.getAsString().
 * 
 * @param cookieValue
 * 				A string representing the form, should
 *				be equal to an earlier use of
 *				CommunityObject.getAsString()  
 * 
 */
function restoreFormFromCookie(cookieValue) {
	var co = new CommunityObject("","","","","");
	co.setFromString(cookieValue);
	
	if(co.isValid()) {
		if(getBodyEditFormDiv(co.getPostingId()) != undefined) {
			showEditForm(co.getPostingId());

			// Set the form values
			var theForm = document.getElementById(co.getFormName());
			if(theForm.body != undefined)
				theForm.body.value = co.getBody();
			if(theForm.body != undefined)
				theForm.title.value = co.getTitle();
			if(theForm.editReason != undefined)
				theForm.editReason.value = co.getEditReason();
				
		}else{
			if(!confirm(ERROR_FORM_NOT_FOUND + "\n\n" + COOKIE_CONFIRM_DELETION))
				deleteCommunityCookie(COMMUNITYCOOKIE_NAME);

		}
		
	}else{
		if(!confirm(COOKIE_RESTORE_FAILED + "\n\n" + COOKIE_CONFIRM_DELETION))
			deleteCommunityCookie(COMMUNITYCOOKIE_NAME);
	}
}

/**
 * Gets the value of the wanted querystring variable,
 * or null if it is not found.
 */
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return null;
}

function GET(argname){
	var query = location.search.substring(1);
	var pairs = query.split("&");
	for(i=0; i<pairs.length; i++){
        key   = pairs[i].split("=")[0];
        value = pairs[i].split("=")[1];
        if(key == argname){
            return value;
        }
    }
    return "";
} 

/**
 * Saves the form info into a cookie, for later processing.
 * It parses the form into a CommunityObject, and saves its
 * string representation into the cookie.
 *
 * @param theForm
 *			The form object 
 * 
 */
function saveCommunityObjectFromForm(theForm) {
	if(theForm != undefined) {
		var bodyString = "";
		var titleString = "";
		var idString = "";
		var editReason = "";

		// Get the form values
		if(theForm.body != undefined)
			bodyString = theForm.body.value;
		if(theForm.body != undefined)
			titleString = theForm.title.value;
		if(theForm.postingId != undefined)
			idString = theForm.postingId.value;
		if(theForm.editReason != undefined)
			editReason = theForm.editReason.value;
		
		// Create the javascript representation of the form		
		var co = new CommunityObject(theForm.id, titleString, bodyString, idString, editReason);
		
		if(co.isValid()) { 
			var coString = co.getAsString();
			
			// Set the object string to a cookie
			setCommunityCookie(COMMUNITYCOOKIE_NAME, co.getAsString(), COMMUNITYCOOKIE_MINUTES_ALIVE);
		}
	}
}


/**
 * A simple javascript object that should
 * represent a community object posting.
 */
function CommunityObject(formName, title, body, postingId, editReason) {
	this.formName = formName;
	this.title = title;
	this.body = body;
	this.postingId = postingId;
	this.editReason = editReason ;
	this.stringDivider = "|#|#|";
	
	// body getter and setter
	this.getBody = function() { return this.body; }
	this.setBody = function(b) { this.body = b; }
	
	// title getter and setter
	this.getTitle = function() { return this.title; }
	this.setTitle = function(t) { this.title = t; }
	
	// form name getter and setter
	this.getFormName = function() { return this.formName; }
	this.setFormName = function(fn) { this.formName = fn; }
	
	// postingId getter and setter
	this.getPostingId = function() { return this.postingId; }
	this.setPostingId = function(pid) { this.postingId = pid; }

	// editReason getter and setter
	this.getEditReason = function() { return this.editReason; }
	this.setEditReason = function(er) { this.editReason = er; }

	// object string representation	
	this.getAsString = function() {
		return this.formName 
			+ this.stringDivider 
			+ this.postingId
			+ this.stringDivider 
			+ this.body
			+ this.stringDivider 
			+ this.title 
			+ this.stringDivider 
			+ this.editReason 
	}
	
	/**
	 * Supposed to update the values from a single string,
	 * using the same pattern as CommunityObject.getAsString()
	 * we can map the values back again.
	 * 
	 * @param s
	 *		The single string containing all values
	 */
	this.setFromString = function(s) {
		// Check that argument is valid
		if(s != undefined && s.indexOf(this.stringDivider) > 0) {
			var splitArray = s.split(this.stringDivider);
			this.formName = splitArray[0];
			
			if(splitArray.length >= 1)
				this.postingId = splitArray[1];
			if(splitArray.length >= 2)
				this.body = splitArray[2];
			if(splitArray.length >= 3)
				this.title = splitArray[3];
			if(splitArray.length >= 4)
				this.editReason = splitArray[4];
		}
	}

	/**
	 * Checks the most vital parts of the object
	 * and decides if it is valid.
	 */
	this.isValid = function() {
		var result = true;
		if(this.body == "" || this.formName == "")
			result = false;
		
		return result;
	}
}
