// this variable give a flexibility maybe
// someone want to get info from another url
var ajaxSearchPath = "/contenttag/js_search.html";

// remember the current tab
currentTabIds = new Object();
paginationSize = 6;
numOfPaginationLinks = 5;
tabStates = new Object();
exceptionString = 'An exception has occurred.'

function resetTabState(richEditorId) {
	var contentType = getCurrentContentType(richEditorId);
	if( tabStates[richEditorId] == null ) 
		tabStates[richEditorId] = new Object();
		
	tabStates[richEditorId][contentType] = {'entityCount': 0, 'entityList': [], 'paginationIndex': 0};
};

function getCurrentTabState(richEditorId) {
	var contentType = getCurrentContentType(richEditorId);
	return tabStates[richEditorId][contentType];
}


function getCurrentContentType(richEditorId) {	
	var tabId = currentTabIds[richEditorId];
	var lastIndex = tabId.lastIndexOf("_");
	tabId = tabId.substring(lastIndex+1, tabId.length);
	return tabId.replace("Tab", "");
}

function getCurrentTagValue(richEditorId) {
	var contentType = getCurrentContentType(richEditorId);
	var elementId = richEditorId + "_$" + contentType + "$tag";
	return $F(elementId);
};

function getCurrentOrderValue(richEditorId) {
	var contentType = getCurrentContentType(richEditorId);
	var elementId = richEditorId + "_$" + contentType + "$order";
	return $F(elementId);
};

function getCurrentTemplateValue(richEditorId) {
	var name = richEditorId + "_$" + getCurrentContentType(richEditorId) + "$template";
	var choices = document.getElementsByName(name)
	for(var i = 0; i < choices.length; i++){
		if(choices[i].checked){
			return choices[i].value
		}
	}
}

function getCurrentSelector(richEditorId) {
	var contentType = getCurrentContentType(richEditorId);
	var elementId = richEditorId + "_$" + contentType + "$selector";
	return $(elementId);
}

function getCurrentPagination(richEditorId) {
	var elementId = richEditorId + "_$" + getCurrentContentType(richEditorId) + "$pagination";
	return $(elementId);
}

function getCurrentRichEditorId(elem) {
	var elementId = elem.id;
	var lastIndex = elementId.lastIndexOf("_");
	return elementId.substring(0,lastIndex);
}

function getCurrentTabId(tabElem) {
	var richEditorId = getCurrentRichEditorId(tabElem);
	
	if( currentTabIds[richEditorId] == null ) 
		currentTabIds[richEditorId] = richEditorId + '_textTab';
	
	return currentTabIds[richEditorId];
}

function setCurrentTabId(tabElem) {
	var richEditorId = getCurrentRichEditorId(tabElem);
	currentTabIds[richEditorId] = tabElem.id;
}

function onClickTab(elem) {
//	if (Prototype.Browser.IE) {
//		alert(onClickTab);
//	}
	
	var currentTabId = getCurrentTabId(elem);
	
	var previousTab = $(currentTabId);
	var previousPanel = $(currentTabId + 'Panel');
	//alert(currentTabId + 'Panel' + ', previousPanel = ' + previousPanel); 
	previousTab.className = '';
	previousPanel.hide();
	
	var currentTab = elem;	
	var currentPanel = $(elem.id + 'Panel')
	currentTab.className = 'active';
	currentPanel.show();
	
	setCurrentTabId(elem);
	// prevent the browser from jumping to be beginning of the page.
	return false;
}



/* ---------------------------------------------------------------------- *\
  Function    : insertWidget()
  Description : insert the widget into the editor.  
  Arguments   : category - the category of the content
  				id - id of the content.  
\* ---------------------------------------------------------------------- */
function insertWidget(richEditorId, category,id){
	var template = getCurrentTemplateValue(richEditorId);
	var url = getWidgetURL(category,id,template)	
	if(url){
		ajaxRequest(url,{ctx:getContextNameInUrl()},insertWidgetCB.curry(richEditorId,category,id,template))
	}
};

var widgetMacroTemplate = new Template("<span class='widget_preview'>#{preview}</span>")

function insertWidgetCB(richEditorId, category,id,template,transport){
	if (!isValidReturn(transport.responseText)) {
		// document.title = quietFail;
		//alert(transport.responseText);
		if (!eval(quietFail)) alert(exceptionString);
		return;		
	} 
	var tag = widgetMacroTemplate.evaluate({'category':category,'id':id,'template':template,'preview':transport.responseText});
	
	//if it's html mode
	if( getViewTextMode(richEditorId) == 0 ) {
		insertHTML(richEditorId,tag);
	} else if( getViewTextMode(richEditorId) == 1 ) {
		insertText(richEditorId,tag);
	}
};

/* ---------------------------------------------------------------------- *\
  Function    : getWidgetURL()
  Description : return the widget url.  
  Arguments   : category - the category of the content.
  				id - id of the content.
  				template - template used to render the widget.  
\* ---------------------------------------------------------------------- */
function getWidgetURL(category,id,template){	
	var url = null
	if(category == 'Photo'){
		url = "/photos/wp/"+template+"-"+id+".html"
	}else if(category == 'PhotoGallery'){
		url = "/photos/wpg/"+template+"-"+id+".html"
	}else if(category == 'Video'){		
		url = "/videos/wv/"+template+"-"+id+".html"
	}
	return contextPath + url	
};


//function dojoOnloadCallback() {
//	alert("Stupid IE.");
//}
//
/* ---------------------------------------------------------------------- *\
  Function    : readTag()
  Description : pass tag definition([widget[category,id,template]]) inside the <span> tag 
  				and inject the actule content.
  Arguments   : inFrame - means that the dom tree is in an iframe tag. be trun in Add/Edit page.   				
  Notes		  : invoke when the blog is load.   
\* ---------------------------------------------------------------------- */ 
function readTag(inFrame){
	// var doc = null
	if(inFrame){
		//resetTabState('photo');
		//resetTabState('photoGalery');
		//resetTabState('video');
	
		// n is defined in wysiwyg.js		
		// doc = document.getElementById("wysiwyg" + n).contentWindow.document
				
	}
	/*
	else{
		doc = document
	}
	
	var spans = doc.getElementsByTagName('span');
	for(var i = 0; i < spans.length; i++){
		if(spans[i].className == 'widget_tag'){
			var m = spans[i].innerHTML.match(/\[widget\[(\w+),(\w+),(\w+)\]\]/)
			if (m) {
				var url = getWidgetURL(m[1],m[2],m[3])
				ajaxRequest(url,{ctx:getContextNameInUrl()},readTagCB.curry(spans[i]));
			}
		}
	}
	*/
};

/*
function readTagCB(widgetTagNode, transport){
	// exception page will starts with '<!DOCTYPE HTML PUBLIC'
	// alert("readTagCB");
	if(isValidReturn(transport.responseText)){
		// widgetTagNode.title = widgetTagNode.innerHTML;
		widgetTagNode.className = 'widget_preview';
		widgetTagNode.innerHTML = transport.responseText;
	}
};
*/

/* ---------------------------------------------------------------------- *\
  Function    : ajaxRequest()
  Description : make an ajax request.
  Arguments   : url - url to query.
  				parameters - query parameters.
  				fp - callback function.
\* ---------------------------------------------------------------------- */ 
function ajaxRequest(url,parameters,fp,richEditorId){
	if(url){
		new Ajax.Request(url,{
			method: 'get',
		  	parameters: parameters,
		  	onSuccess: function(transport,json) {				
				fp(transport,richEditorId)
		  	},
			onFailure: function(){ alert('Something went wrong when fetching the url '+url) }
		})	
	}
};

function onClickSearch(button)  {
	var richEditorId = getCurrentRichEditorId(button);
	resetTabState(richEditorId);
	tagSearch(richEditorId);
}

function tagSearch(richEditorId){
	var tag = getCurrentTagValue(richEditorId);
	var order = getCurrentOrderValue(richEditorId);
	var paginationIndex = getCurrentTabState(richEditorId).paginationIndex;
	var contentType = getCurrentContentType(richEditorId);
	
	document.getElementById(richEditorId + "_$" + contentType + "$results").style.display="block";
	getCurrentSelector(richEditorId,contentType).innerHTML = "<div class=\"loading_bar\"></div>";
    
	ajaxRequest( contextPath + ajaxSearchPath,
				{order: order,
				keywords: tag,
				category: contentType,
				ctx: getContextNameInUrl(),
				startIndex: paginationIndex * paginationSize,
				maxRows: paginationSize
				},
				tagSearchCallback, richEditorId)
};

function tagSearchCallback(transport, richEditorId){
	if(isValidReturn(transport.responseText)){
		
		dict = eval('('+transport.responseText+')');
		
		getCurrentTabState(richEditorId).entityCount = dict['entityCount'];
		getCurrentTabState(richEditorId).entityList = dict['entityList'];
		
		// reset the pagination index value
		paginate(richEditorId);
		
		
		if(getCurrentTabState(richEditorId).entityList.length == 0){
			getCurrentSelector(richEditorId).innerHTML = "No Content Matched."
		}else{			
			resetWidgetSelector(richEditorId);
			document.getElementById("$" + contentType + "$sortpage").style.display = "block";
		}
	}else{
		getCurrentSelector(richEditorId).innerHTML = "No Content Matched."
	}
};

var currentPageTemplate = new Template('<strong>#{start} - #{end}</strong> of #{count}');
var paginationLinkTemplate = new Template('<a class=\"#{className}\" onClick=\"onClickPaginationLink(\'#{richEditorId}\',#{index})\"">#{display}</a>');


function paginate(richEditorId) {
	getCurrentPagination(richEditorId).innerHTML = "";
	var entityCount = getCurrentTabState(richEditorId).entityCount;
	var paginationIndex = getCurrentTabState(richEditorId).paginationIndex;
	
	start = entityCount == 0 ? 0 : (paginationIndex * paginationSize) + 1;
	end = entityCount == 0 ? 0 : start + paginationSize - 1;
	if (end > entityCount) end = entityCount;
  
	prevIndex = paginationIndex - 1;
	nextIndex = paginationIndex + 1;
	lastIndex = Math.ceil(entityCount / (paginationSize * 1.0)) - 1;
  
  	//alert("entityCount:" + entityCount);
  	//alert("paginationIndex:" + paginationIndex);
  	//alert("lastIndex:" + lastIndex);
  	//alert("pagination:" + getCurrentPagination(richEditorId));
  	
	if (paginationIndex > 0) {
		getCurrentPagination(richEditorId).insert(paginationLinkTemplate.evaluate({richEditorId:richEditorId,index: 0, display: 'first', className: 'RTE_first_link'}), getCurrentPagination(richEditorId));
		getCurrentPagination(richEditorId).insert(paginationLinkTemplate.evaluate({richEditorId:richEditorId,index: prevIndex, display: 'prev', className: 'RTE_prev_link'}), getCurrentPagination(richEditorId));
	}
	
	getCurrentPagination(richEditorId).insert(currentPageTemplate.evaluate({start: start, end: end, count: entityCount}), getCurrentPagination(richEditorId));
	
	if ( paginationIndex < lastIndex ) { 
		getCurrentPagination(richEditorId).insert(paginationLinkTemplate.evaluate({richEditorId:richEditorId,index: nextIndex, display: 'next', className: 'RTE_next_link'}), getCurrentPagination(richEditorId));
		getCurrentPagination(richEditorId).insert(paginationLinkTemplate.evaluate({richEditorId:richEditorId,index: lastIndex, display: 'last', className: 'RTE_last_link'}), getCurrentPagination(richEditorId));
	}
  	
/*	
	for(var i = 0; i < entityCount; i += paginationSize){
		if (i/paginationSize == paginationIndex) {
			getCurrentPagination().insert("" + (i/paginationSize+1), getCurrentPagination());
		} else {
			getCurrentPagination().insert(paginationLinkTemplate.evaluate({index: i/paginationSize, display: (i/paginationSize+1)}), getCurrentPagination());
		}
	}
*/
//	alert("entityCount = " + entityCount + ", paginationIndex = " + paginationIndex);
//	alert(getCurrentPagination(richEditorId).innerHTML);
}

/* ---------------------------------------------------------------------- *\
  Function    : resetWidgetSelector()
  Description : recreate the widget selector
  Arguments   : startIndex - from which we will create the clickable widget.    
\* ---------------------------------------------------------------------- */ 
function resetWidgetSelector(richEditorId){
	getCurrentSelector(richEditorId).innerHTML = ""
	entityList = getCurrentTabState(richEditorId).entityList
//	alert("resetWidgetSelector: " + entityList);
	if (entityList == null)
		return;
	
	var len = Math.min(entityList.length, paginationSize)	
	for(var i = 0; i < len; i++){
		createClickableWidget(richEditorId, getCurrentSelector(richEditorId), entityList[i])
	}
}

function onClickPaginationLink(richEditorId,startIndex){
	getCurrentTabState(richEditorId).paginationIndex = startIndex;
	tagSearch(richEditorId);	
}

/* ---------------------------------------------------------------------- *\
  Function    : createClickableWidget()
  Description : Create Clickable Widget which can be selected by user.
  Arguments   : container - container element used to hold the return content.
  				content - content instance.
  Notes       : format for content is defind by the "json" layout in the correspond template file.
\* ---------------------------------------------------------------------- */
var clickableWidgetTemplate = new Template("<a onclick=\"insertWidget('#{richEditorId}','#{category}','#{id}')\" title='#{category} - #{title}'><img src='#{thumbnail}' width='80' height='60' alt='#{category} - #{title}'/></a>")

function createClickableWidget(richEditorId, container,content){
	content.richEditorId = richEditorId;
	container.insert(clickableWidgetTemplate.evaluate(content),container)
};

/* ---------------------------------------------------------------------- *\
  Function    : isValidReturn()
  Description : Test whether the response is validated.
  Arguments   : content - response text.
  Notes       : server may return error msg for the widget loading, verify them before insert into the page.
\* ---------------------------------------------------------------------- */
function isValidReturn(content){
	return !content.strip().startsWith("<!DOCTYPE HTML PUBLIC") && (content.indexOf(exceptionString) == -1)
};

/* ---------------------------------------------------------------------- *\
  Function    : getContextNameInUrl()
  Description : Return the ctx value in the url.  
\* ---------------------------------------------------------------------- */
function getContextNameInUrl(){
	var i = currentCtx.indexOf('Context')
	if(i != -1){
		currentCtx = currentCtx.substring(0,i) 
	}
	return currentCtx
};

function richEditorToggleDisplay(elem, tagPostfix) {
	var richEditorId = getCurrentRichEditorId(elem);
	var tagId = richEditorId + '_' + tagPostfix;
	toggleDisplay(tagId);
}

function fireRichEditor(richEditorId) {
	var browserName = navigator.appName;
	
	// only do it in firefox
	// for the reason that can not delete the first picture
	// in the begining of edit
	
	if(browserName == 'Netscape') {
		var richEditor = document.getElementById(richEditorId);
		var doc = richEditor.contentWindow.document;
		
	    doc.designMode = "off";
		doc.body.contentEditable = false;
		
		doc.designMode = "on";
		doc.body.contentEditable = true;
	}
}
