// Content Box Class
// To be commented..
function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

function isObject(object) {
    return object && typeof object == "object";
}

function isNull(object) {
    return object === null;
}


/** ContentBoxManager
 *
 **/ 


var ContentManager;

function ContentBoxManager() {

    var currentPreviewObject;
  	var databuffer;
    var iCurrGroupID;
  	var iEventCount;
    var iLastInsertPos;
    var insertBoxButtonPressed;
    var iUpdatePreview;
    var iAreaIsPopulated;
    var posHash;
    var posHashID;
  	var strCurrEventType;
  	var strCurrContainerID;
  	var strEventLog;
  	var strModeEditType;
    var strPageAreaSelected;
    var strLastAreaGroupID;
    var selectedGroupHandle;
    var displayAutoComplete;
  
    // initialize
  	this.databuffer = '';
  	this.iEventCount = 0;
  	this.strCurrEventType = '';
  	this.strCurrContainerID = '';
  	this.strEventLog = '';
  	this.strModeEditType = '';
    this.strPageAreaSelected = '';
    this.iCurrGroupID = 0;  
    this.iUpdatePreview = 0;
    this.strLastAreaGroupID = '';
    this.iLastInsertPos = -1;
    this.insertBoxButtonPressed = 0;
    this.currentPreviewObject = false;
    this.selectedGroupHandle = '';
    this.iAreaIsPopulated = 0;

    this.posHash = new Array();
    this.posHashID = new Array();

    // public methods
    this.initBoxType = initBoxType;
    this.displayAutoComplete = displayAutoCompletePanel;
}

function displayAutoCompletePanel(){
  
    if(document.getElementById("availableContent"))
        document.getElementById("availableContent").style.display = "block";

    if(document.getElementById("ddSubjects"))
        document.getElementById("ddSubjects").style.display = "block";

    if(document.getElementById("ddMatchSubjects"))
        document.getElementById('ddMatchSubjects').style.display = 'block';
}

function initBoxType(type) {
	
    this.databuffer = '';
    this.strModeEditType = type;
}


if( !isObject(ContentManager) )
    ContentManager = new ContentBoxManager();


function ContentBox(instName, id) {

	var name;
	this.name = instName+id;
	
	var nid;
	this.nid = id;
	
	var boxType;
	
	var useHeading;
	
	var heading;
	
	var type;
	
	var count;
	
	var format;
	
	var subject;
	
	var HTML;
	this.HTML = '';
	
	var id;
	var contentId;
	var handleId;
	var headerId;
	var fileName;
	
	var location;
	
	var contents;
	
	var parent;
	
	var rendered;
	this.rendered = false;
	
	var textareaID;
	this.textareaID = false;
	
	var textareaContentsID;
	this.textareaContentsID = false;


}

ContentBox.prototype.getEl = function() {
	return document.getElementById(this.id);
}

ContentBox.prototype.render = function (div) {


	if (insertPosition) {
		if (insertPosition.id.indexOf('sub')>-1) {
			insertPosition = document.getElementById(insertPosition.id+'b');
			arr = new Array();
			if (insertPosition.childNodes.length > 1) {
				insertPosition.insertBefore(div, insertPosition.childNodes[1]);
			} else {
				insertPosition.appendChild(div);
			}
		} else {
			var parent = insertPosition.parentNode;
			pos = parent.childNodes.length;
			for (i=0; i<parent.childNodes.length; i++) {
				if (parent.childNodes[i] == insertPosition) {
					pos = i;
					break;
				}
			}
			if(pos+1 == parent.childNodes.length) {
				parent.appendChild(div);
			} else {
				parent.insertBefore(div, parent.childNodes[pos+1]);
			}
		}
	}
}

ContentBox.prototype.generateBox = function() {


	var group = "grp" + this.nid;
	this.id = group;

  //alert( "type:".this.boxType);

	switch (this.boxType) {
		// Module
		case 'module':
			handle  = document.createElement('div');
			handle.className = 'ddhandle';
			handle.id = 'handle'+group;
			this.handleId = handle.id;
			handle.style.textAlign = 'right';
			handle.style.display = 'none';
			handle.innerHTML = '<span align="right" class="ddnhandle"><a href="javascript:removeBox(\''+group+'\')">Remove</a></span>';

			div = document.createElement('div');
			div.className = this.theme;
			div.id = group;

			ediv = document.createElement('div');
			ediv.className = 'enter';
			ediv.id = 'enter' + (MSJS.dd.columns.length+1);
			ediv.style.display = 'none';
			this.enterId = ediv.id;

			cdiv = document.createElement('div');
			cdiv.className = 'contentBlock';
			cdiv.id        = 'contentBlock'+group;
			this.contentId = cdiv.id;
			cdiv.innerHTML = this.data;
			div.className = 'moduleBox';
			div.appendChild(handle);

			div.appendChild(cdiv);
			div.appendChild(ediv);

			this.HTML = div;
		break;
		// Freeform HTML
		case 'HTML':


			var div = document.createElement('div');
			div.id = group;

			if (!this.heading) {
				this.heading = 'Please enter a heading or uncheck the \"Use Heading\" box';
			}

			h2  = document.createElement('h2');
			h2.className = 'subhead';
			h2.id = 'grphead'+group;
			h2.innerHTML = this.heading;
			this.headerId = h2.id;
			if (!this.useHeading) {
				h2.style.display = 'none';
			}

			var textarea = document.createElement('div');
			textarea.id = textarea.name = 'simpleEditor' + (this.nid);
			textarea.className = 'simpleEditor';

      var gcontent;

      if( isObject(ContentManager) ){
          gcontent = ContentManager.databuffer;
      }
      else{
          gcontent = '';
      }
 
      if(gcontent!='' && !isNull(gcontent))
    			textarea.innerHTML = gcontent ;
      else 
			   textarea.innerHTML = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et "+
  			"dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. "+
  			"Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat "+
  			"cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";



			textarea.style.width = '100%';
			textarea.style.minHeight = '50px';
			textarea.title = "Click here to edit the contents of this box";

			var handle  = document.createElement('div');
			handle.className = 'ddhandle';
			this.handleId = 'handle'+group;
			handle.id = this.handleId;
			handle.style.textAlign = 'right';
			handle.style.display = 'none';
			handle.innerHTML = '<span align="right" class="ddnhandle"><a href="javascript:editBox(\''+group+'\')">Edit</a> | <a href="javascript:removeBox(\''+group+'\')">Remove</a></span>';




			var input = document.createElement('input');
			input.type = 'hidden';
			input.id = input.name = textarea.id + 'Contents';
			handle.appendChild(input);

			this.textareaID = textarea.id;
			this.textareaContentsID = input.id;

			var cdiv = document.createElement('div');
			cdiv.className = 'contentBlock';
			
			var div = document.createElement('div');
			div.className = this.theme;
			div.id = group;

			var ediv = document.createElement('div');
			ediv.className = 'enter';
			ediv.id = 'enter' + (MSJS.dd.columns.length+1);
			this.enterId = ediv.id;
			div.appendChild(handle);
			div.appendChild(h2);
			cdiv.appendChild(textarea);
			div.appendChild(cdiv);
			div.appendChild(ediv);

			this.HTML = div;
		break;
		// Automatic Content
		case 'automatic':
			type    = strAutomaticContentType;//document.getElementById("automaticContentType").value;
			count   = document.getElementById("templateContentCount").value;
			display = document.getElementById("contentDisplayTemplate").value;
			heading = document.getElementById("templateContentHeading").value;
			subject = document.getElementById("automaticContentSubject").value;

				if (!this.heading) {
					this.heading = 'Please enter a heading or uncheck the \"Use Heading\" box';
				}
				h2  = document.createElement('h2');
				h2.className = 'subhead';
				h2.id = 'grphead'+group;
				h2.innerHTML = this.heading;
				this.headerId = h2.id;
				if (!this.useHeading) {
					h2.style.display = 'none';
				}
				handle  = document.createElement('div');
				handle.className = 'ddhandle';
				handle.id = 'handle'+group;
				this.handleId = handle.id;
				handle.style.textAlign = 'right';
				handle.style.display = 'none';
				handle.innerHTML = '<span align="right" class="ddnhandle"><a href="javascript:editBox(\''+group+'\')">Edit</a> | <a href="javascript:removeBox(\''+group+'\')">Remove</a></span>';

				div = document.createElement('div');
				div.className = this.theme;
				div.id = group;

				ediv = document.createElement('div');
				ediv.className = 'enter';
				ediv.id = 'enter' + (MSJS.dd.columns.length+1);
				ediv.style.display = 'none';
				this.enterId = ediv.id;
				
				cdiv = document.createElement('div');
				cdiv.className = 'contentBlock';
				cdiv.id        = 'contentBlock'+group;
				this.contentId = cdiv.id;
				
				div.appendChild(handle);
				div.appendChild(h2);

				div.appendChild(cdiv);
				div.appendChild(ediv);

				this.HTML = div;

				// Make the request
				var d = new Date()
				var t = d.getTime()

        var rtitle = "";
        if( document.getElementById("automaticContentTitle") )
            rtitle = document.getElementById("automaticContentTitle").value;

				var url = '/admin/ajax/browser?searchType=automatic&subject=' + encodeURIComponent(this.subject) + '&ts=' + t + '&type=' + this.type + '&format='+this.format +
						  '&boxID=' + this.contentId + '&count='+this.count+'&adminview=1&title=' + rtitle;


        for( i=0; i < custom_search_ele.length; i++)
            url += getSearchParamValuePair(custom_search_ele[i]["id"],custom_search_ele[i]["type"] );

				_this = this;
				var callbackFun = 
					{ 
						success: function(o) {_this.updateBox(o)}, 
						failure: function(o) {_this.updateBox(o)}
					}; 
	    
				var request = YAHOO.util.Connect.asyncRequest('GET', url, callbackFun);		

		break;
		case 'custom':
			this.id="customgrp" + (this.nid);
			this.group = "customgrp" + (this.nid);
			if (!this.heading) {
			    this.heading = 'Please enter a heading or uncheck the \"Use Heading\" box';
			}
			h2  = document.createElement('h2');
			h2.className = 'subhead';
			h2.id = 'grphead'+this.id;
			h2.innerHTML = this.heading;
			this.headerId = h2.id;
			if (!this.useHeading) {
			    h2.style.display = 'none';
			}
			handle  = document.createElement('div');
			handle.className = 'ddhandle';
			handle.id = 'handle'+group;
			this.handleId = handle.id;
			handle.style.textAlign = 'right';
			handle.style.display = 'none';
			handle.innerHTML = '<span align="right" class="ddnhandle"><a href="javascript:editBox(\''+
							   this.group+'\')">Edit</a> | <a href="javascript:removeBox(\''+this.group+'\')">Remove</a></span>';
	
			div = document.createElement('div');
			div.className = this.theme;
			div.id = this.group;

				
			ediv = document.createElement('div');
			ediv.className = 'enterc';
			ediv.id = 'enterc' + (MSJS.dd.columns.length+1);
			ediv.style.height = '2px';
			ediv.innerHTML = '&nbsp;';
			
			mediv = document.createElement('div');
			mediv.className = 'enter';
			mediv.id = 'enter' + (MSJS.dd.columns.length+1);
			mediv.style.display = 'none';
			this.enterId = mediv.id;
			
			cdiv = document.createElement('div');
			cdiv.className = 'contentBlock';
			cdiv.id        = 'contentBlock'+group;
			cdiv.style.minHeight = '60px';
			contentId = cdiv.id;
			
			div.appendChild(handle);
			div.appendChild(h2);
		
			cdiv.appendChild(ediv);

			div.appendChild(cdiv);
			div.appendChild(mediv);
			this.HTML = div;


      var previewArea;
      if(document.getElementById('previewCustomContentArea')){
    			previewArea = document.getElementById('previewCustomContentArea');
    	    previewArea.innerHTML = '';
      }else{
          previewArea = document.createElement('div');
          previewArea.setAttribute("id", 'previewCustomContentArea');
    	    previewArea.innerHTML = '';
          document.getElementById('previewPane').appendChild(previewArea);
      }  

			var note = document.createElement('p');
			note.className = 'note';
			note.innerHTML = 'Drag items from the search pane to populate this content box.';
			previewArea.appendChild(note);
			previewArea.appendChild(div);

			customSearchBox = div.id;
		break;
	}
}

/***
    This is used to create a new box when previewing default (latin) text

    bool updateBox(object o)

*/

ContentBox.prototype.updateBox = function(o) {


	var rs = eval(o.responseText);
	var box = rs[0];

	box = document.getElementById(box);
	/*
	 * Response codes:
     * 200: Ok
	 * 404: Subject not found
	 * 405: No content found under subject
	 */
	if (rs[1] != 200) {
		this.hasContent = false;
		var message;
		switch (rs[1]) {
		case 404:
			message = 'Invalid subject entered';
		break;
		case 405:
			message = 'No contents with given type were found under given subject';
		break;
		}
		var p = document.createElement('p');
		p.className = 'errorBox';
		p.innerHTML = message;
		box.appendChild(p);
		return;
	}
	this.hasContent = true;

	box.innerHTML = rs[2];
	return true;
}

/**
 * Content Blob
 */
function contentBlob() {


	// Object ID
	var id;
	// CMS ID
	var cmsID;
	// Display format
	var format;
}
