/*
 * Codestars user control pannel
 * By Floris Weijenburg (http://www.florisweijenburg.nl)
 * Copyright (c) 2008 Floris Weijenburg
 * All programming rights reserved.
*/  

CS.DOM.tools = function() 
{
	this.waited = false;
	this.sLoc = config.rootFolder + 'ajax/ajaxDataHandler.php';
}
 
CS.DOM.tools.prototype.LockElements = function(elements)
{
	for(var i=0; i<=elements.length-1; i++)
	{
		var element = $(elements[i]);
		element.disabled = true; 
	}
}
 
CS.DOM.tools.ShowDialog = function(modalTitle, modalContentUrl, contentType)
{
	YAHOO.namespace("stocklist.container");
	
	YAHOO.stocklist.container.wait = new YAHOO.widget.Panel("wait", 
	{
		width: "auto",
		fixedcenter: true,
		close: true,
		draggable: false,
		zindex: 4,
		modal: true
	});
	
	YAHOO.stocklist.container.wait.setHeader(modalTitle);
	
	if(contentType == 'external') 
	{
		this.LoadExternalContent(modalContentUrl);
	}
	else if(contentType == 'html') 
	{
	   YAHOO.stocklist.container.wait.setBody(modalContentUrl);
       YAHOO.stocklist.container.wait.render(document.body);
       YAHOO.stocklist.container.wait.show();
	}
}
	
CS.DOM.tools.LoadExternalContent = function(url)
{
    new Ajax.Request(url,
    {
        method:'get',
        onSuccess: function(transport)
        {
           
           YAHOO.stocklist.container.wait.setBody(transport.responseText);
           YAHOO.stocklist.container.wait.render(document.body);
           YAHOO.stocklist.container.wait.show();
        }
    });
}
 
CS.DOM.tools.BuildMessageForm = function()
{
	new CS.DOM.tools.Pause(1,5);
	YAHOO.util.Event.onDOMReady(function() 
	{
		var jsonString = $('jsonReplyData').value;
		var messageData = jsonString.evalJSON()[0];
			
		$('messageReceiver').value = messageData.userNameReceiver;
		$('messageSubject').value = 'RE:' + messageData.subject;
		$('messageBody').value = "\n\nReactie op bericht: \n" + messageData.message;
	});
}

/* Wait functionality */

CS.DOM.tools.Pause = function(duration, busy)
{
	this.duration= duration * 1000;
	this.busywork = null; // function to call while waiting.
	this.runner = 0;
	
	if (arguments.length == 2) {
		this.busywork = busy;
	}

	CS.DOM.tools.Pause.prototype(this.duration);
}

CS.DOM.tools.Pause.prototype = function(duration)
{
	if((duration == null) || (duration < 0)) {return;}

	var later = (new Date()).getTime() + duration;

	while(true){
  		if ((new Date()).getTime() > later) {
        	break;
     	}
     
		this.runner++;
	     
		if (this.busywork != null) {
			this.busywork(this.runner);
		}
	} 
}

CS.DOM.tools.prototype.UpdateItem = function(row, command, id, pluginId)
{
	var i;
	var itemContent;
	var columns = row.getElementsByTagName('td'); 
	var identifyData = new Object();
			
	identifyData.userSessId = config.userSessId;
	identifyData.itemId = id;
	identifyData.pluginId = pluginId;
	
	for(i=0; i < columns.length; i++)
	// First we need to find the message td in the row element
	{
		if(columns[i].className == 'messageContainer')
		{
			itemContent = columns[i].innerHTML;
			columns[i].innerHTML = '';
			
			// Now we change the message td into an textarea
			// And add an update button
			this.CreateUpdateElement(columns[i], itemContent, command, identifyData);
		} 
	}
}

CS.DOM.tools.prototype.CreateUpdateElement = function(containerElement, content, command, identifyData)
{
	var textarea = document.createElement('textarea');
	var updateBtn = document.createElement('input');
	var date = new Date();
	var uniqueId = "update-"+date.getDate()+""+date.getMinutes()+""+date.getSeconds();
	
	textarea.value = ReplaceAll(content, '<br>', '');
	textarea.style.width = '100%';
	textarea.id = uniqueId;
	textarea.name = identifyData.itemId;

	updateBtn.className = uniqueId;
	updateBtn.lang = command; 
	updateBtn.identify = identifyData;
	updateBtn.type = 'submit';
	updateBtn.value = 'Opslaan';
	
	/*
	 * If we do not use the tiny_mce text editor we can use AJAX. 
	 * Tiny_mce needs an synchroon POST request to post it's BBcode	
	 */
	if(command == 'UpdateReply')
	{
		YAHOO.util.Event.addListener(updateBtn, "click", this.CallCommand, this, false); 
		updateBtn.type = 'button';
	}

	containerElement.appendChild(textarea);
	containerElement.appendChild(updateBtn);

	// Ajust the height of the textarea
	var appendedTextarea = $(uniqueId);
	var row = appendedTextarea.parentNode.parentNode;

	row.style.height = appendedTextarea.scrollHeight + "px";
	appendedTextarea.style.height = appendedTextarea.scrollHeight + "px";
	appendedTextarea.focus();
}

CS.DOM.tools.prototype.CallCommand = function(e, obj)
{
	var updateData = new Object();
	var textarea = $(this.className);
	var updateValue = textarea.value;
	
	// Linux uses another newline code, let's replace the default one
	updateValue = updateValue.replace('\n', '\r\n'); 
	
	updateData.identify = this.identify;
	updateData.value = updateValue;
		
	new Ajax.Request( 
	obj.sLoc, 
	{
	  	method: 'get',
	  	parameters: 
	  	{
			cmd: this.lang, 
		  	value: Object.toJSON(updateData)
		},
        onSuccess: function(transport)
        {
			(textarea.parentNode).innerHTML = ReplaceAll(textarea.value, '\n', '<br />\n');
        }
        .bind(textarea)
	});
}

CS.DOM.tools.prototype.MergeHtmlCollection = function(container, tag1, tag2)
{
	var ary = [];
	var elements1 = container.getElementsByTagName(tag1);
	var elements2 = container.getElementsByTagName(tag2);
	
	for(var zxc0=0;zxc0<elements1.length;zxc0++)
	{
		ary.push(elements1[zxc0]);
	}
	
	for(var zxc1=0;zxc1<elements2.length;zxc1++)
	{
		ary.push(elements2[zxc1]);
	}
	
	return ary;
}

CS.DOM.tools.prototype.DeleteItem = function(row, command, id)
{
	var tableRow = row;
	var userIsSure = confirm
	('Weet je zeker dat je dit item wilt verwijderen?'); 
	
	if(userIsSure) 
	{
		// Let's "delete" the item by fading it away
		var ani = new YAHOO.util.Anim(row, 
		{
			opacity: {from: 1, to: 0 }
		}, 1, YAHOO.util.Easing.easeOut);
		
		ani.animate();
		
		// Remove TR node after fadeout
		ani.onComplete.subscribe(function() 
		{
			tableRow.remove(tableRow);
			// Now we call our delete command	
			// ...
			 
			var delData = new Array();
			
			delData[0] = config.userSessId;
			delData[1] = id;
			
			new Ajax.Request(
			this.sLoc,
		    {
		        method:'get',
				parameters: 
			  	{
				  	cmd: command, 
				  	value: delData.toJSON()
	
				}
		    });	
		}.bind(this, command, id)); 	
	}
}

CS.DOM.tools.prototype.ItemAnswered = function(row, command, id, type)
{
    // Let's change the row's background colour
    row.style.background = '#cefe9b';

    var itemData = new Array();

    itemData[0] = config.userSessId;
    itemData[1] = id;
    itemData[2] = type;

    new Ajax.Request(
    this.sLoc,
    {
        method:'get',
        parameters:
        {
            cmd: command,
            value: itemData.toJSON()
        },
        onSuccess: function()
        {
            if(type == "reply")
            {
                location.reload(true);
            }
        }.bind(type)
    });
}

CS.DOM.tools.prototype.ChangeElementType = function(element, type)
{
	// Generate the new element type
	var newElement = document.createElement(type);
	
	// Copy the attribute values
	newElement.id = element.id;
	newElement.name = element.name;
	
	// Replace the element
	(element.parentNode).appendChild(newElement);
	(element.parentNode).removeChild(element);
	
	// Done!
	newElement.focus();
}