var request;
var mod_close="CloseModule";
var mod_minimize="MinimizeModule";
var mod_maximize="MaximizeModule";
var mod_swap="SwapModule";
var mod_subscription="SubscriptionModule";
var mod_movedown="MoveModule_down";
var mod_moveup="MoveModule_up";
var mod_movetop="MoveModule_top";
var mod_movebottom="MoveModule_bottom";
var sch_max = "sch_max";
var sch_min = "sch_min";

function initXMLHttpRequest() {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
	}
    else if (window.ActiveXObject) {
        request = new ActiveXObject('Microsoft.XMLHTTP');
	}
	return(request);
}

function loadXMLDoc(url,request,handler) {
	request.onreadystatechange = handler;// assign handler. 
	request.open("GET", url, true);
	request.send(null);//null data for GET call
}

function ajax_handler() {
	processReqChange(request);
}

function processReqChange(request) {
	// only if req shows "complete"
    if (request.readyState == 4) {
        // only if "OK"
        if (request.status == 200) {
			parseResponseXML(request);
		} else {
			//alert('There was a problem retrieving content:\n' + request.statusText); // use only for debugging.
		}
	}
}

function displayBlock(module, moduleParam, contentID, catObj, result) {
	
	hideAllMenus();//This hides the menu which is created when clicked on move image
	var containerID = contentID;
	if(moduleParam == sch_max || moduleParam == sch_min)
        {
                if(countschvalue==1)
                {
                        moduleParam = SCH_Home_Value;
                }
                else
                {
                        var temp = document.getElementById('select_'+contentID);
                        moduleParam = temp.options[temp.selectedIndex].value;
                }
        }
	
	// If dropdown value was empty, exit immediately.
	if (module == mod_swap || module == mod_subscription) {
		if (moduleParam == "") {
			return;
		}
	}

	var hasJs = catObj.hasJs;
	if (module == mod_swap) {
		for (i=0; i < categoryList.length;i++) {
			if (moduleParam == categoryList[i].catId) {
				hasJs = categoryList[i].isJavascript;
				break;
			}
		}
	}

	var useAjax = (config_ajax == "AJAX" ? true : false);
	var useIframe = (config_ajax == "IFRAME" ? true : false);
	if (config_ajax == "AJAX_IFRAME") {
		useAjax = true;
		if (hasJs == "true") {
			useIframe = true;
			useAjax = false;
		}
	}

	if (allow_override == 'yes') {
		useAjax = (page_config_ajax == "AJAX" ? true : false);
		useIframe = (page_config_ajax == "IFRAME" ? true : false);
		if (page_config_ajax == "AJAX_IFRAME") {
			useAjax = true;
			if (hasJs == "true") {
				useIframe = true;
				useAjax = false;
			}
		}
	}

	var color = getColorForScheme(catObj.scheme);
	var refresh = ((module == mod_minimize || module == mod_close) ? "n" : "y");
			 
	var url = "/personalization/AjaxController.jsp?contentID="+contentID+"&module="+module+"&categoryID="+catObj.id+"&subscriptionID="+contentarea[contentID]+"&selectedID="+moduleParam+"&refresh="+refresh+"&scheme="+catObj.scheme;
	var toolsHTML = document.getElementById("tools_"+contentID).innerHTML;
	
	if (module == mod_minimize) {
		if (useAjax || useIframe) {
			insertContent(contentID,''); // insert empty content
			// display icon
			toolsHTML = toolsHTML.replace(/min/g,'max');
			toolsHTML = toolsHTML.replace(/MinimizeModule/g,'MaximizeModule');
			//toolsHTML = toolsHTML.replace(/Minimise/g,'Maximise');
			toolsHTML = toolsHTML.replace(alt_texts["min"],alt_texts["max"]);
		}
		document.getElementById("tools_"+contentID).innerHTML=toolsHTML;
		catObj.icon_min="max";
	}
	else if (module == mod_maximize){
		catObj.icon_min="min";
	}
	else if (module == mod_moveup || module == mod_movedown  || module == mod_movetop || module == mod_movebottom){
			
			var num_steps = 1;
			var offset = -1;
			var portlet_pos = parseInt(moduleParam);
			var portlet_absolute_pos = parseInt(moduleParam);
			var portlet_max_pos = total_count_medical;

			if (moduleParam > 1000)	{
				portlet_pos = moduleParam-1000;
				portlet_max_pos = total_count_more;
			}
			if (module == mod_movetop)	{
				num_steps = portlet_pos-1;
			}
			else if (module == mod_movebottom)	{
				num_steps = portlet_max_pos-portlet_pos;
			}
			if (module == mod_movebottom || module == mod_movedown){
				offset = 1;
			}
			for (i=1;i<=num_steps ;i++ ){
				
				for (j in contentarea_pos ){
					if (contentarea_pos[j] == (portlet_absolute_pos+offset)){
						var prev_portlet_subID = j;
					}
					if (contentarea_pos[j] == portlet_absolute_pos){
						var current_portlet_subID = j;
					}
				}
				for (j in content_placeholder ){
					if (content_placeholder[j] == prev_portlet_subID){
						var prev_portlet_containerID = j;
					}
					if (content_placeholder[j] == current_portlet_subID){
						var current_portlet_conatinerID = j;
					}
				}
				var temp_portlet_content = document.getElementById("placeholder_"+prev_portlet_containerID).innerHTML;
				var current_portlet_content = document.getElementById("placeholder_"+current_portlet_conatinerID).innerHTML;
				//document.getElementById("placeholder_"+prev_portlet_containerID).innerHTML = '';
				//document.getElementById("placeholder_"+current_portlet_conatinerID).innerHTML = '';
				document.getElementById("placeholder_"+prev_portlet_containerID).innerHTML = current_portlet_content;
				document.getElementById("placeholder_"+current_portlet_conatinerID).innerHTML = temp_portlet_content;
				
				var temp_portlet_position = contentarea_pos[current_portlet_subID];
				contentarea_pos[current_portlet_subID]=contentarea_pos[prev_portlet_subID];
				contentarea_pos[prev_portlet_subID]=temp_portlet_position;
				 
				var temp_portlet_placeholder = content_placeholder[prev_portlet_containerID];
				content_placeholder[prev_portlet_containerID]=content_placeholder[current_portlet_conatinerID];
				content_placeholder[current_portlet_conatinerID]=temp_portlet_placeholder;
		
				portlet_absolute_pos = portlet_absolute_pos+offset;
			}
	}
	
	else if (module == mod_close) {
		for (i=0; i < categoryList.length; i++ ) {
			if (catObj.id == categoryList[i].catId) {
				categoryList[i].flag = "0";
				break;
			}
		}
		if (useAjax || useIframe) {
				//document.getElementById("portlet_"+contentID).style.display ='none';
				//browsetype = navigator.appName;
				//if(browsetype == "Microsoft Internet Explorer"){
					for (j in content_placeholder ){
						if (content_placeholder[j] == contentID){
							document.getElementById("placeholder_"+j).style.display ='none';
						}					
					}
				//}
				
		}
		
		if(page_config_move == 'true'){
				for (j in contentarea_pos ){
				if (moduleParam < 1000 && contentarea_pos[j] < 1000 && contentarea_pos[j] > moduleParam){
				contentarea_pos[j] = parseInt(contentarea_pos[j])-1;
				}
				else if (moduleParam > 1000 && contentarea_pos[j] > 1000 && contentarea_pos[j] > moduleParam){
				contentarea_pos[j] = parseInt(contentarea_pos[j])-1;
				}
				else if ((contentarea_pos[j] == moduleParam)) {
				contentarea_pos[j] = 0;
				}
			}
			
			if (moduleParam > 1000)	{
				total_count_more--;
			}
			else{
				total_count_medical--;
			}
		}
	}
	else if (module == mod_subscription) {
		var listElements = catObj.list.split("."); 
		var listName = listElements[1];

		i = 0;
		while ( i < categoryList.length ) {
			var slpCatId = categoryList[i].slpCatId;
			var catId = categoryList[i].catId;
			if (catId == catObj.id) {
				url += "&twinCategoryID=" + slpCatId;
				break;
			}
			i++;
		}
	}
	document.getElementById("tools_"+contentID).innerHTML=toolsHTML;

	if (useIframe) {
		// Super duper Iframe way
		if(module != mod_minimize && module != mod_moveup && module != mod_movedown && module != mod_movetop && module != mod_movebottom) {
			insertContent(contentID,text_loading);
		}

		url += "&useIframe=true";

		var oDiv = document.createElement('div');
		oDiv.setAttribute("id",'hiddendiv_'+contentID);
		oDiv.style.width = '1px';oDiv.style.height = '1px';oDiv.style.visibility = 'hidden';oDiv.style.top = '0px';
		oDiv.style.left = '0px';oDiv.style.position = 'absolute';

		document.body.appendChild(oDiv);
		oDiv.innerHTML = "<iframe id='"+contentID+"' name='"+contentID+"' height='1' width='1'></iframe>";
		loadIframe(contentID,url);//TODO: will content get auto replaced?
	}
	else if (useAjax) {
		// Cool ajax way
		if(module != mod_minimize && module != mod_moveup && module != mod_movedown && module != mod_movetop && module != mod_movebottom) {	
			insertContent(contentID, text_loading);
		}
		request = initXMLHttpRequest();
		loadXMLDoc(url,request,ajax_handler);
	}
	else {
		// Traditional PB way
		var subscriptionID = contentarea[contentID];
		if (module == mod_minimize) {
			url = servletURL + "?module=com.med.phd.CustomizeProfileModule&action=minimizeSubscription&subscriptionID="+subscriptionID;
		}
		else if (module == mod_maximize) {
			url = servletURL + "?module=com.med.phd.CustomizeProfileModule&action=maximizeSubscription&subscriptionID="+subscriptionID;
		}
		else if (module == mod_close) {
			url = servletURL + "?module=com.med.phd.CustomizeProfileModule&action=cancelSubscription&subscriptionID="+subscriptionID;
		}
		else if (module == mod_swap) {
			url += "&reload=y&pageURL="+servletURL;
		}
		else if (module == mod_subscription) {
			url += "&reload=y&pageURL="+servletURL;
		}
		window.location = url;
		return false;
	}
}

function insertContent(contentID,content) {
	document.getElementById("portlet_content_"+contentID).innerHTML = "<div class=\"portlet_content_left_shadow\"><div class=\"portlet_content_margin\"></div><div class=\"portlet_inner_content\">" + content + "</div><div class=\"portlet_content_margin\"></div>";
}

function parseResponseXML(request) {
	if(request.responseXML != null) {
		var response = request.responseXML.documentElement;
		var error = response.getAttribute("isError");
		var contentID = response.getElementsByTagName("contentID")[0].childNodes[0].nodeValue;
		var body = response.getElementsByTagName('body')[0].firstChild.data;
		var catID = response.getElementsByTagName('id')[0].firstChild.data;	
		
		if(error == 'yes') {
			insertContent(contentID,body);
		}
		else {
			var title = '';
			if (response.getElementsByTagName('title')[0].firstChild != null) {
				title = response.getElementsByTagName('title')[0].firstChild.data;
			}
			var module = '';
			if (response.getElementsByTagName('module')[0].firstChild != null) {
				module = response.getElementsByTagName('module')[0].firstChild.data;
			}
			var close = '';
			if (response.getElementsByTagName('close')[0].firstChild != null) {
				close = response.getElementsByTagName('close')[0].firstChild.data;
			}
			var minimize = '';
			if (response.getElementsByTagName('minimize')[0].firstChild != null) {
				minimize = response.getElementsByTagName('minimize')[0].firstChild.data;
			}
			var subscriptionID = '';
			if (response.getElementsByTagName('subscriptionID')[0].firstChild != null) {
				subscriptionID = response.getElementsByTagName('subscriptionID')[0].firstChild.data;
			}
			var selectedID = '';
			if(response.getElementsByTagName('selectedID')[0].firstChild != null) {
				selectedID = response.getElementsByTagName('selectedID')[0].firstChild.data;
			}
			if (module == mod_maximize) {
				dd = document.getElementById('select_'+contentID);
				if (dd != null && dd !='') {
					selectedID = dd.value;
				}
			}

			var hasJs = '';
			if (response.getElementsByTagName('useIframe')[0].firstChild != null) {
				hasJs = response.getElementsByTagName('useIframe')[0].firstChild.data;
			}
			var scheme = '';
			if (response.getElementsByTagName('scheme')[0].firstChild != null) {
				scheme = response.getElementsByTagName('scheme')[0].firstChild.data;
			}
			var catListType = '';
			if (response.getElementsByTagName('catlist')[0].firstChild != null) {
				catListType = response.getElementsByTagName('catlist')[0].firstChild.data;
			}
			// If not minimized and not closed
			if(module!=mod_close && module!=mod_minimize) {

				contentarea[contentID] = subscriptionID;
				insertContent(contentID,body);
				
				var catFromResponse = new catObject(catID,title,minimize,'',close,'',catListType,scheme,hasJs);

				update_container_header(contentID,selectedID,catFromResponse,scheme);
			}
		}
	}
}

function loadIframe(iframeName, url) {
	if ( window.frames[iframeName] ) {
		window.frames[iframeName].location = url;   
		return false;
	}
	else {	
		return true;
	}
}

function insertIt( module, selectedID, contentID, subscriptionID, catObj, scheme) {
	//alert("modulein Insertit"+module);
	//alert("subscriptionID after ajax call"+subscriptionID);
	if(module != mod_close && module != mod_minimize && module != mod_moveup && module != mod_movedown && module != mod_movetop && module != mod_movebottom) {
		var _y = document.getElementById('portlet_content_'+contentID);
		var  _x = window.frames[contentID].document.body;	
		
		contentarea[contentID] = subscriptionID;
		if (module == mod_maximize) {
			dd = document.getElementById('select_'+contentID);
			if (dd != null && dd !='') {
				selectedID = dd.value;
			}
		}
		_y.innerHTML = "<div class=\"portlet_content_left_shadow\"><div class=\"portlet_content_margin\"></div><div class=\"portlet_inner_content\">" + _x.innerHTML + "</div><div class=\"portlet_content_margin\"></div>";
		update_container_header(contentID, selectedID, catObj, catObj.scheme);
	}
	
}

function insertItError( module, selectedID, contentID, subscriptionID, catObj, scheme) {
		var _y = document.getElementById('portlet_content_'+contentID);
		var  _x = window.frames[contentID].document.body;	

		contentarea[contentID] = subscriptionID;
		if (module == mod_maximize) {
			dd = document.getElementById('select_'+contentID);
			if (dd != null && dd !='') {
				selectedID = dd.value;
			}
		}
		_y.innerHTML = "<div class=\"portlet_content_left_shadow\"><div class=\"portlet_content_margin\"></div><div class=\"portlet_inner_content\">" + _x.innerHTML + "</div><div class=\"portlet_content_margin\"></div>";
}

