
var EC_XML = 'xmlformcontainer';
var EC_LOTUS = 'lotusframe';
var EC_MEMO = 'memocontainer'; 
var EC_FILE = 'filecontainer';
var EC_UPLOAD = 'uploadContainer';
var EC_STATUS = 'uploadStatusContainer';

var IMG_MEMO = 'files/memo/memo.png';
var IMG_FILE = 'files/attachment/attachment.png';
var IMG_UP   = 'files/bullet_up/bullet_up.png';
var IMG_DOWN = 'files/bullet_down/bullet_down.png';
var IMG_SHOWDOCS = 'files/docs_show/docs_show.gif';
var IMG_HIDEDOCS = 'files/docs_hide/docs_hide.gif';
var IMG_AJAX = 'files/loader/loader.gif';


var EC_UPLOADID = null;
var EC_APPLICATIONID = null;
var tmpObj = null;
var statCounter = 0;
//var calendarList = new Array();

// Hashtable with the Ajax response docs
var responseHash = null;



if (Prototype.Browser.IE) {
	var bversion = (navigator.userAgent.toLowerCase().match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
	if (bversion >= 6) {
	    var _cssfile = __base+'/files/ie-fix/ie-fix.css';
	    //var _cssfile = '/reykjanes/ie-fix.css';
	    var _css = new Element('link', {href: _cssfile, 'type':'text/css', 'rel':'stylesheet', 'media':'screen'});
	    document.getElementsByTagName("head")[0].appendChild(_css);
	}
}



function __ping() {
    var url = __base + '/portal/home.html';
    var img = document.createElement('img');
	img.setAttribute('src', url);
	img.setAttribute('border','0');
	img.setAttribute('width','0');
	img.setAttribute('height','0');
	$(img).setStyle({visibility: 'hidden'});
    $(document.body).appendChild(img);
}

function setMenu() {
	try {
		var path = window.location.pathname;
		var page = path.substring(path.lastIndexOf('/') + 1);
		
		// Get the menu container
		var items = $('main-nav').descendants();
		if (items != null) {
			items.each(function(item) {
				if (typeof(item.href) != 'undefined') {
					var currPage = item.href.substring(item.href.lastIndexOf('/') + 1);
					if (currPage.startsWith(page)) {
						var li = $(item).up('li');
						if (li != null) {
						    $(li).addClassName('active');
						}
						return;
					}
				}
			});
		}
	} catch (ex) {}
}

function recoverAccount(sender, obj) {
	var email = obj.value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)) {
		sender.disabled = true;
		var img = $('ajaximg');
		if (img == null) {
			var img = new Image();
			img.src = __base+'/'+IMG_AJAX;
			img.id = 'ajaximg';
			img.setAttribute('border',0);
			img.setAttribute('hspace',10);
			$('recovery').appendChild(img);
		} else {
			img.show();
		}
		
		communityProxy.recoverUserPassword(email,recoverAccountHandler);
	} 
}

function recoverAccountHandler(msg) {
	if (msg.startsWith('Error')) {
		alert(msg.substr(6,msg.length));
		$('reqsender').disabled = false;
		var img = $('ajaximg');
		if (img != null) {
			img.hide();
		}
	} else {
		$('recovery').hide();
		var rd = $('recoverymessage');
		rd.innerHTML = msg;
		rd.show();
		
	}
}

function lsButtonsHide() {
	try {
	var frame = $('lotusframe').contentDocument;
	if (frame == null || typeof(frame) == 'undefined')  {
		frame = window.frames['lotusform'].window.document;
	}
	var list = $A(frame.getElementsByTagName('button'));
	var buttons = Array();
	list.each(function(item) {
		item = $(item);
		if (item.name.startsWith('PAGE')) {
			buttons.push(item);
		}
	});
	buttons.each(Element.hide);
	} catch (ex) {}
}

function showResponses(id, img) {
	if (id !=null) {
		
		if (responseHash == null) {
			responseHash = new Hash();
		}
			
		// Change the image and class
		var clsName = 'docopen';
		if (img.id == '') {
			img.id = 'i_'+id;
		}
		if ($(img.id).hasClassName(clsName)) {
			img.src = IMG_SHOWDOCS;
			img.toggleClassName(clsName);
			
			// Find our rowIndex
			var tbl = $('tblcases');
			var trIndex = $(id).rowIndex;
			var trTotal = tbl.rows.length;
			// Delete next cells with classname parentRow
			var index = trIndex+1;
			while(index < trTotal) {
				var row =  tbl.rows[index];
				if (typeof(row) != 'undefined' && row.className == 'parentRow') {
					tbl.deleteRow(index);
				} else	{
					break;
				}
			}
			
			// Remove as expanded from cookie
			var data = readCookie('caselist');
			if (data !=  null) {
				var ids = data.split('|').without(id).join('|');
				eraseCookie('caselist');
				createCookie('caselist',ids,7*12);
			}
			
		} else  { 
			img.src = IMG_HIDEDOCS;
			img.toggleClassName(clsName);
			// If the response are available in the Hashtable with use that
			// instead of making unneeded ajax call
			var hashObj = responseHash.get(id); 
			if (typeof(hashObj) != 'undefined') {
				handleResponseDocuments(hashObj);
			} else {
				communityProxy.getResponseDocuments(id, handleResponseDocuments);
			}
			
			// Remember that this is expanded
			var data = readCookie('caselist');
			if (data == null) {
				data = id;
			} else {
				data +='|'+id;
			}
			var ids = data.split('|').uniq().join('|');
			eraseCookie('caselist');
			createCookie('caselist',ids,7*12);
		}
	}
}

function handleResponseDocuments(data) {
	if (data != null && data.length>0) {
		// Hash the response for later usage
		responseHash.set(data[0].parentId,data);
		for(var i=0;i<data.length;i++) {
			createResponseRow(data[i]);
		}
	}
}

function createResponseRow(obj, rowindex) {
	var tbl = $('tblcases');
	var parentIndex = $(obj.parentId).rowIndex;
	var tr = tbl.insertRow(parentIndex+1);
	tr.className = 'parentRow';	
	
	var td1 = tr.insertCell(-1);
	
	var td3 = tr.insertCell(-1);
	var td4 = tr.insertCell(-1);
	var td5 = tr.insertCell(-1);
	var td6 = tr.insertCell(-1);
	var td7 = tr.insertCell(-1);
	var td8 = tr.insertCell(-1);
	
	
	var img = document.createElement('img');
	img.setAttribute('border','0');
	img.setAttribute('valign','absmiddle');
	img.style.marginRight = '5px';
	img.style.verticalAlign = 'middle';
		
	var link = document.createElement('a');
	if (obj.dataType == 'MEMO') {
		link.setAttribute('href', 'memo.html?id='+obj.itemId);
		img.setAttribute('src', IMG_MEMO);
	} else if (obj.dataType == 'ATTACHMENT') {
		link.setAttribute('href', 'attachment.html?id='+obj.itemId);
		img.setAttribute('src', IMG_FILE);
	}
	var text = document.createTextNode(obj.title);
	link.style.textDecoration = 'none';
	link.appendChild(text);
	td3.style.paddingLeft = '5px';
	td3.className = 'title';
	td3.appendChild(img);
	td3.appendChild(link);
	
	// Check if the doc is a response document
	if (obj.reply==true) {
		var s = document.createElement('span');
		s.className = 'reply';
		var rText = "("+Trans.late('js.response')+")";
		s.appendChild(document.createTextNode(rText));
		td3.appendChild(s);
	}
	
	
	td4.setAttribute('align','right');
	td4.appendChild(document.createTextNode('-'));
	
	var dmod = new Date(obj.dateModified).format('j.n.Y');
	td5.appendChild(document.createTextNode(dmod));
	td5.setAttribute('align','right');
	
	var dcre = new Date(obj.dateCreated).format('j.n.Y');
	td6.appendChild(document.createTextNode(dcre));
	td6.setAttribute('align','right');
	
	td7.appendChild(document.createTextNode('-'));
	td7.setAttribute('align','right');
	
	var status = '';
	if (obj.status == 'CLOSED') {
		status = Trans.late('status.closed');
	} else if (obj.status == 'OPEN') {
		status = Trans.late('status.open');
	} else {
		status = Trans.late('status.notset');
	}
	
	td8.setAttribute('align','right');
	td8.appendChild(document.createTextNode(status));
	
}

function doPassChange(show) {
  if (show) {
    Effect.Fade('profile-settings');
    Effect.Appear('profile-password',{ queue: 'end' });
    
    setTimeout(function() {$('oldpass').focus();}, 2000);

  } else {

   Effect.Fade('profile-password');
   Effect.Appear('profile-settings',{ queue: 'end' });

  }
}


function enableActionButtons() {
	try {
		try {
			$('addattachment').disabled = false;
		} catch (ex) {}
		try {
			$('addmemo').disabled = false;
		} catch (ex) {}
	} catch (ex){}
}

function setAction(obj) {
	$('form_action').value = obj.name;
}


function formSubmit(form, groupname) {
	toggleActionButtons(false, groupname);
}

function toggleActionButtons(bShow, groupname) {
	var buttonItems;
	if (typeof(groupname) != 'undefined') {
		var strItems = 'input.'+groupname;
		buttonItems = $$(strItems);
	} else {
		buttonItems = $$('input.actionButton');
	}
		
	for(var i=0;i<buttonItems.length;i++) {
		if (bShow) {
			buttonItems[i].disabled = false;
		} else {
			buttonItems[i].disabled = true;
		}
		
	}
}

function breakOut() { 
	if (top.location != location) {
   	 top.location.href = document.location.href ;
  }
}


function openPDF(application_id) {
	var url = 'communityfiles/?id='+application_id+'&req=pdf&force';
	location.href = url;
}

function openAttachment(attachment_id) {
	var url = 'communityfiles/?id='+attachment_id+'&req=att&force';
	location.href = url;
}


/** 
  	Register User functions
**/

function doLookup(obj) {
	
	var regExp = /^(\d{10})$/;
	if (regExp.test(obj.value)) {
		communityProxy.searchRegistry(obj.value,setRegistryValues);
	} 
}

function setRegistryValues(data) {
	if (data != null) {
		$('fullname').value = data.fullname;
		$('address').value = data.address;
		$('email').focus();
	}
}



/** 
	Memo functions for eCommunity
**/

function addMemo() {
	try {
		$(EC_MEMO).removeClassName('hidden');
		Effect.Grow(EC_MEMO);
			
		var buttonItems = $$('input.actionButton');
		for(var i=0;i<buttonItems.length;i++) {
			buttonItems[i].disabled = true;
		}
	} catch (ex) {
		alert(ex.Message);
	}
	
	try {
		Effect.Squish(EC_XML);
	} catch (Exception)  {
		try {
			Effect.Squish(EC_LOTUS);
		} catch (Exception){}
	}
	
}

function getMemoResults(memoId) {
	if (memoId != null && memoId.length == 32) {
				
		// Clear last memo input
		$('memoTitle').value = '';
		$('memoBody').value = '';
		
		if (tmpObj != null) {
			tmpObj.memoId = memoId;	
			// Create the table entry
			addDocumentEntry(tmpObj, 'memo');
			// Finally show the form again
			cancelMemo();	
		}
		
	} else { 
		alert('Memo could not be added.  Server error.');
	}
	
	// Show the buttons again
	toggleActionButtons(true, 'memoButton');
}

function sendMemo(applicationId, isFinished) {
	var memoTitle = $('memoTitle').value;
	var memoText = $('memoBody').value;
	
	if (memoTitle == '' || memoText == '') {
		alert(Trans.late('js.memo'));
		return false;
	}
	
	
	// Create the Memo object
	var memo = {
		memoId:"NULL",
  		title:memoTitle,
  		contents:memoText,
  		applicationId:applicationId
	};
	
	// Set it to tmpObj for the callback Obj to use
	tmpObj = memo;
	// Hide the buttons
	toggleActionButtons(false, 'memoButton');
	communityProxy.addMemo(memo,isFinished,getMemoResults);
}



function cancelMemo() {
	try {
		Effect.Grow(EC_XML);
	} catch (Exception) {
		try {
			Effect.Grow(EC_LOTUS);
		} catch (Exception) {}
	}
		
	Effect.Squish(EC_MEMO);
	var buttonItems = $$('input.actionButton');
	for(var i=0;i<buttonItems.length;i++) {
		buttonItems[i].disabled = false;
	}
}

function addDocumentEntry(obj, type) {
	if (obj != null &&  type == 'memo') {
	
		var tbl = $('memoTbl');
		var tr = tbl.insertRow(1);
		
		var rowCount = tbl.rows.length;
		if ((rowCount % 2) == 0) {
			tr.className = 'c1';
		} else {
			tr.className = 'c0';
		}
		
		var tdImage = tr.insertCell(-1);
		var tdTitle = tr.insertCell(-1);
		var tdCreated = tr.insertCell(-1);
		var tdModified = tr.insertCell(-1);
		var tdStatus = tr.insertCell(-1);
		
		var img = document.createElement('img');
		img.setAttribute('src', IMG_MEMO);
		img.setAttribute('border','0');
		img.setAttribute('title','Memo');
		tdImage.appendChild(img);
		
		var link = document.createElement('a');
		link.setAttribute('href', 'memo.html?id='+obj.memoId);
		var text = document.createTextNode(obj.title);
		link.appendChild(text);
		tdTitle.className = 'title';
		tdTitle.appendChild(link);
		
		var dateNow = new Date();
		var dateString = dateNow.format('j.n.Y G:i');
		
		tdCreated.setAttribute('align','right');
		tdModified.setAttribute('align','right');
		tdCreated.appendChild(document.createTextNode(dateString));
		tdModified.appendChild(document.createTextNode(dateString));
		
		if ($('memoTableContainer').hasClassName('hidden')) {
			$('memoTableContainer').removeClassName('hidden');
			Effect.Grow('memoTableContainer');
		}
			
	}
	
	if (obj != null && type == 'attachment') {
	
		var tbl = $('memoTbl');
		var tr = tbl.insertRow(1);
		
		var rowCount = tbl.rows.length;
		if ((rowCount % 2) == 0) {
			tr.className = 'c1';
		} else {
			tr.className = 'c0';
		}
		
		var tdImage = tr.insertCell(-1);
		var tdTitle = tr.insertCell(-1);
		var tdCreated = tr.insertCell(-1);
		var tdModified = tr.insertCell(-1);
		var tdStatus = tr.insertCell(-1);
		
		var img = document.createElement('img');
		img.setAttribute('src', IMG_FILE);
		img.setAttribute('border','0');
		img.setAttribute('title','Attacment');
		tdImage.appendChild(img);
		
		var link = document.createElement('a');
		link.setAttribute('href', 'attachment.html?id='+obj.attachmentId);
		var text = document.createTextNode(obj.title);
		link.appendChild(text);
		tdTitle.className = 'title';
		tdTitle.appendChild(link);
		
		var dateNow = new Date();
		var dateString = dateNow.format('j.n.Y G:i');
		
		tdCreated.setAttribute('align','right');
		tdModified.setAttribute('align','right');
		tdCreated.appendChild(document.createTextNode(dateString));
		tdModified.appendChild(document.createTextNode(dateString));
		
		if ($('memoTableContainer').hasClassName('hidden')) {
			$('memoTableContainer').removeClassName('hidden');
			Effect.Grow('memoTableContainer');
		}
	
	}
	
}

function addAttachment(applicationId) {
	$(EC_FILE).removeClassName('hidden');
	Effect.Grow(EC_FILE);
		
	var buttonItems = $$('input.actionButton');
	for(var i=0;i<buttonItems.length;i++) {
		buttonItems[i].disabled = true;
	}
	
	try {
		Effect.Squish(EC_XML);
	} catch (ex) {
		try {
			Effect.Squish(EC_LOTUS);
		} catch (ex){}
	}
	
}

function checkAttachment() {
	return true;
}

function cancelAttachment() {
	try {
		Effect.Grow(EC_XML);
	} catch (Exception) {
		try {
			Effect.Grow(EC_LOTUS);
		} catch (Exception) {}
	}
	
	Effect.Squish(EC_FILE);
	var buttonItems = $$('input.actionButton');
	for(var i=0;i<buttonItems.length;i++) {
		buttonItems[i].disabled = false;
	}
}


/*** 
* 
*  File Upload functions
*
***/

function getUnid() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var string_length = 32;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function checkStatus() {
	uploadProxy.getStatus(doStatus);
 }


/**
	Checks if the upload was successful and then get a hold 
	on the file servlet side.
*/
function checkUploadFinishedStatus() {
	if (EC_UPLOADID == null) {
		alert('Upload failed.  No file on endpoint ');
		return;
	}
	$('uploadStatusMsg').innerHTML = Trans.late('js.uploadprocess');
	communityProxy.isUploadedFileAvailable(EC_UPLOADID, finishUpload);
}

function finishUpload(data) {
	if (data != null && data == true) {
		// Now we actually tell the endpoint to create the attachment and save to db.
		$('uploadStatusMsg').innerHTML = Trans.late('js.uploadprocess');
		sendAttachment();
	} else {
		alert(Trans.late('js.uploaderror'));
	}
	EC_UPLOADID = null;
}

function sendAttachment() {

	// Create the Attachment object
	var attachment = {
		attachmentId:"NULL",
  		title:$('fileTitle').value,
  		comment:$('fileInfo').value,
  		applicationId:EC_APPLICATIONID
	};

	// Set it to tmpObj for the callback Obj to use
	tmpObj = attachment;

    communityProxy.addAttacment(attachment,getAttachmentResults);
}

function getAttachmentResults(data) {
	if (data != null && data.length == 32)  {
		$('uploadStatusMsg').innerHTML = Trans.late('js.uploaddone');
		
		
		if (tmpObj != null) {
			tmpObj.attachmentId = data;	
			// Create the table entry
			addDocumentEntry(tmpObj, 'attachment');
			// Finally show the form again
			cancelAttachment();
			
			// Reset the upload field for a new file
			Effect.Squish(EC_STATUS);
			Effect.Grow(EC_UPLOAD);
			$('uploadStatusMsg').innerHTML = Trans.late('js.uploadstatus');
			updateProgressBar(0);
			
			// Clear the input fields
			$('inputFile').value = '';
			$('fileTitle').value = '';
			$('fileInfo').value = '';
		}
		
		
	} else {
		$('uploadStatusMsg').innerHTML = Trans.late('js.uploaderror');
	}
	
}

function doStatus(stat) {
	statCounter++;
    if (stat.status == 2) {
       	updateProgressBar(100);
  	    window.setTimeout("checkUploadFinishedStatus()", 1000);
       	return;
     }

     if (stat.status == 3) {
         alert("An error has occured! " + stat.message);
         return;
     }

     if (stat.status == 4) {
         alert("An error has occured! " + stat.message);
         return;
     }

     // do something with the percentage (nice loading bar, simply show the percentage, etc)
     updateProgressBar(stat.percentComplete);
     window.setTimeout("checkStatus()", 500);
  }

function updateProgressBar(percentage) {
    // make sure you set the width style property for uploadProgressBar, otherwise progress.style.width won't work
    var progress = document.getElementById("uploadProgressBar");
    var indicator = document.getElementById("uploadIndicator");
    var maxWidth = parseIntWithPx(progress.style.width) - 4;
    var width = percentage * maxWidth / 100;
    indicator.style.width = width + "px";
    var perc = document.getElementById("uploadPercentage");
    perc.innerHTML = percentage + "%";
}

function parseIntWithPx(str) {
    var strArray = str.split("p");
    return parseInt(strArray[0]);
}

function startUploadMonitoring(form, application_id) {
 		
	// Check the file title
	if (form.fileTitle.value == '') {
		alert(Trans.late('js.uploadtitle'));
		$('fileTitle').focus();
		return false;
	}
	
	if (form.inputFile.value == '') {
		alert(Trans.late('js.uploadfile'));
		return false;
	}
	
	var unid = getUnid();
	// Make the unique upload ID available globally
	EC_UPLOADID = unid;
	EC_APPLICATIONID = application_id;
	
	// Get the correct upload path
	var path = window.location.pathname;
	var prefix = path.substring(0,(path.lastIndexOf('/')));
    
	var action = prefix+'/upload?application_id='+application_id+'&unid='+unid;
	form.action = action;
	
	// Make the status div visible
	Effect.Grow(EC_STATUS);
	Effect.Squish(EC_UPLOAD);
		
	$('uploadStatusMsg').innerHTML = Trans.late('js.uploadstatus');
	window.setTimeout("checkStatus()", 800);
	return true;
 }



// Simulates PHP's date function
Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (replace[curChar])
			returnStr += replace[curChar].call(this);
		else
			returnStr += curChar;
	}
	return returnStr;
};
Date.replaceChars = {
	shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
	longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
	
	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replace.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replace.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { return "Not Yet Supported"; },
	// Week
	W: function() { return "Not Yet Supported"; },
	// Month
	F: function() { return Date.replace.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 11 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replace.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { return "Not Yet Supported"; },
	// Year
	L: function() { return "Not Yet Supported"; },
	o: function() { return "Not Supported"; },
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return "Not Yet Supported"; },
	g: function() { return this.getHours() == 0 ? 12 : (this.getHours() > 12 ? this.getHours() - 12 : this.getHours()); },
	G: function() { return this.getHours(); },
	h: function() { return (this.getHours() < 10 || (12 < this.getHours() < 22) ? '0' : '') + (this.getHours() < 10 ? this.getHours() + 1 : this.getHours() - 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Supported"; },
	O: function() { return (this.getTimezoneOffset() < 0 ? '-' : '+') + (this.getTimezoneOffset() / 60 < 10 ? '0' : '') + (this.getTimezoneOffset() / 60) + '00'; },
	T: function() { return "Not Yet Supported"; },
	Z: function() { return this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return "Not Yet Supported"; },
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
}



function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(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) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


function removeAttachment(id, obj) {
	if (confirm(Trans.late('js.deleteatt'))) {
		obj.key = id;
		tmpObj = obj;
		communityProxy.deleteAttachment(id,removeAttachmentHandler);
	}
}


function deleteMessage(id) {
	if (confirm(Trans.late('js.delmessage'))) {
		tmpObj = id;
		communityProxy.deleteMessage(id, deleteMessageHandler);
	}
}

function deleteMessageHandler(obj) {
	if (obj != null && obj == true) {
		try {
			var id = 'ul-messsage-'+tmpObj;
			Effect.Fade(id, { duration: 3.0 });
		} catch (ex) {alert(ex.Message);}
	}
} 

function repaintMessages() {
	var trs = $('messagelist').rows;
	for(var i=0;i<trs.length;i++) {
		if ((i % 2) == 0) {
			trs[i].className = 'c1';
		} else {
			trs[i].className = 'c0';
		}
	}
}

function removeAttachmentHandler(obj) {
	if (obj != null && obj == true) {
		if (tmpObj != null) {
			var o = tmpObj;
			tmpObj = null;
			var td = o.b.parentNode;
			td.innerHTML = '';
			var uploadObj = document.createElement('input');
			uploadObj.setAttribute('req',o.r);
			uploadObj.setAttribute('type','FILE');
			uploadObj.name = o.n;
			uploadObj.id = o.n;
			td.appendChild(uploadObj);
			
			// Delete the attachment row in the subdocs list
			try {
				var t = $('sub_'+o.key);
				$(t.parentNode).remove();
			} catch (ex) {}
			
		} 
	} else {
		alert(Trans.late('js.nodelete'));
	}
}

function toggleBox(obj) {
    var div = $(obj).up('div');
	var item  = $(obj).next('p');
	if (item != null) {
		Effect.toggle(item, 'appear');
		var img = item.visible() ? __base+'/files/arrow/up.gif' : __base+'/files/arrow/down.gif';
		div.setStyle({
			background: '#e0e0e0 url('+img+') top right no-repeat'  				
		});
	}
}

function guidance(el) {
    var item = $(el).next();
    if (item.style.display == 'none' || item.style.display == '') {
        item.style.display = 'block';
    } else {
        item.style.display = 'none';   
    }
}

function setCaseStatusBox(caseId) {
    var action = 'casestatus';
    var uri = 'ec_xml.html?action='+action;
    var data = {_class: 'net.gopro.ecommunity.webquery.CaseStatusQuery', _action: action};
    
    data.case_id = caseId;
    
    new Ajax.Request(uri, {
	    method: 'post',
	    onSuccess: drawCaseStatus,
	    parameters: {data: Object.toJSON(data)}
 	});
}

function drawCaseStatus(transport) {

    var obj = transport.responseJSON;
    var error = obj.data.error;
	if (!Object.isUndefined(error)) {
	    alert(error);
		return;
	}
    
    var div = $('casestatusbox');
    var old_ul = $('caseflow');
    if (old_ul != null) {
        old_ul.remove();
    }
	var data = obj.data;
	var list = data.statusflow.status;
    
    
    if (list != null && Object.isArray(list) && list.length > 0) {
    
        var ul = new Element('ul', {id:'caseflow'});
        
        list.each(function(item) {
        
            //var status = item.content.toLowerCase();
            //var statusTranslated = Trans.late('status.'+status);
            var status = item.content;
            var prevStatus = item.laststatus;
            var process = item.process;
            var prevProcess = item.previous;
            
            var li = new Element('li', {'class':process});
            if (prevProcess != null) {
                var span = new Element('span', {'class':prevProcess}).update(status);
                li.appendChild(span);
            } else {
                li.update(status);
            }
            
            ul.appendChild(li);
        
        });
        
        div.appendChild(ul);
        Effect.Appear(div);
            
        
    } else {
        Effect.Fade(div);
    }
}

function setCase(id, tr) {
    
    var tbl = $('tblcases');
    for (var i=0;i<tbl.rows.length;i++) {
        var row = tbl.rows[i];
        if ($(row).hasClassName('selrow')) {
            $(row).removeClassName('selrow');
        }
    }
    $(tr).addClassName('selrow');
    if (id != null) {
        setCaseStatusBox(id);
    }
}


function setLanguage(trans, lang) {
    if (lang != null) {
        communityProxy.setUserLanguage(lang,setLanguage);
    } else {
        window.location.reload();
    }
} 

function toggleAjax(containerId, status, text) {
    var pId = 'pajax-'+containerId;
    
    if (status == true) {
        var pAjax = new Element('p', {id:pId, 'class': 'ajaxpanel'}).update(text);
        $(pAjax).setStyle({
          color: 'green',
          textAlign: 'right'
        });

        var imgId = 'ajaximg-'+containerId;
    	var img = new Image();
    	img.src = IMG_AJAX;
    	img.id = imgId;
    	img.setAttribute('border',0);
    	img.setAttribute('hspace',10);
    	$(img).setStyle('verticalAlign','center');
    	pAjax.appendChild(img);
    	$(containerId).appendChild(pAjax);
    } else {
        $(pId).remove();
    } 
}

function formNavClick(obj) {
    var _o = 'forms-open';
    var _c = 'forms-closed';

    var li = $(obj).up('li');
	if (li != null && li.hasClassName(_c)) {
	    $(li).removeClassName(_c);
	    $(li).addClassName(_o);
	} else if (li != null && li.hasClassName(_o)) {
	    $(li).removeClassName(_o);
	    $(li).addClassName(_c);
	}
}

Event.observe(window,'load', breakOut); 
Event.observe(window,'load', setMenu);




