//The number of results per page.
var NUM_RESULTS = "20";

//To cancel
var bCancel = false;

//To check when it is saved or not.
var isSaved = false;

//The id of the hightlight object.
var highlightsId;

//Flexigrid Object.
var highlightsFlexigrid = null;

// Issues list grid Object
var gridObj = null;

//Hide the success msg or error msg by default.
hideElement("formSuccessMessages");

/*
 * Populate the highlights list
 */
function showHighlightsList (highlightsList) {
	if (highlightsList !== null && highlightsList.length > 0) {
		var highlightsListBody = $("highlights_list_tbody");
		showElement("highlights_head");
		hideElement("emptyMessage");
		if (highlightsListBody) {
			var rowCount = 0;
			var cellFuncs = [
			        function (highlightsList) {
			        	rowCount++;
			        	return rowCount + ".";
			        },
			        function (highlightsList) {
				        return highlightsList.title;
			        }, function (highlightsList) {
				        return highlightsList.displayOrder;
			        }, function (highlightsList) {
				        var data = "No";
				        if (highlightsList.enabled == "true") {
					        data = "Yes";
				        }
				        return data;
			        }, function (highlightsList) {
				        return highlightsList.createdOn;
			        }, function (highlightsList) {
				        return highlightsList.updatedOn;
			        },
			        function (highlightsList) {
			        	var data = '<a href="javascript:void(0);" onclick="getHighlights(' + highlightsList.id + ');">';
			        	alert(data);
				        data += 'Edit </a>';
				        return data;
			        }];

			DWRUtil.addRows("highlights_list_tbody", highlightsList, cellFuncs, {
			    rowCreator : function (options) {
				    var row = document.createElement("tr");
				    if (parseInt(options.rowIndex, 10) % 2 === 0) {
					    row.className = "even";
				    } else {
					    row.className = "odd";
				    }
				    return row;
			    },
			    cellCreator : function (options) {
				    var td = document.createElement("td");
				    if (options.cellNum == 2) {
						td.align = "center";
					} else if (options.cellNum == 3) {
						td.align = "center";
					} 
				    return td;
			    }
			});
		}
	} else {
		showElement("emptyMessage");
		hideElement("highlights_head");
	}

}
/*************End List*************************/
/*************Start Edit*************************/

//To Refresh the data.
function clearInputData () {
	DWRUtil.setValue("id", "");
	DWRUtil.setValue("title", "");
	DWRUtil.setValue("scrollingText", "");
	DWRUtil.setValue("scrollingTextFontSize", "");
	DWRUtil.setValue("scrollingTextColor", "");
	DWRUtil.setValue("description", "");
	DWRUtil.setValue("rte_description", "");
	DWRUtil.setValue("displayOrder", "");
	DWRUtil.setValue("titleFontSize", "");
	DWRUtil.setValue("titleColor", "");
	myEditor.setEditorHTML("");
	$("enabled").checked = "true";
}
/*
 * Populate the Highlights data
 */
function showHighlights (highlightsView, message) {
	if (message !== undefined) {
		$("formSuccessMessages").innerHTML = message;
		showElement("formSuccessMessages");
	} else {
		hideElement("formSuccessMessages");
	}
	if (highlightsView !== null) {
		DWRUtil.setValue("id", highlightsView.id);
		DWRUtil.setValue("title", highlightsView.title);
		DWRUtil.setValue("description", highlightsView.description);
		myEditor.setEditorHTML(highlightsView.description);
		DWRUtil.setValue("displayOrder", highlightsView.displayOrder);
		DWRUtil.setValue("titleFontSize",  highlightsView.titleFontSize);
		DWRUtil.setValue("titleColor",  highlightsView.titleColor);
		DWRUtil.setValue("scrollingText", highlightsView.scrollingText);
		DWRUtil.setValue("scrollingTextFontSize", highlightsView.scrollingTextFontSize);
		DWRUtil.setValue("scrollingTextColor", highlightsView.scrollingTextColor);
		if (highlightsView.enabled == "true") {
			$("enabled").checked = "true";
		} else {
			$("enabled").checked = "";
		}
		// to show the preview boxes for title and scrolling text.
		showTextPreview('title');
		showTextPreview('scrollingText');
	}
}
// hide the Administrator Menu
/*
 * Get the highlights data from the data base
 */
function getHighlights (id) {
	hideElement("formSuccessMessages");
	clearInputData();
	hideElement("highlights_list");
	showElement("highlights_edit");

	// initially hide the preview field sets.
	jQuery("#title_preview_fieldset").addClass("hidden");
	jQuery("#scrolling_text_preview_fieldset").addClass("hidden");
	
	if (id !== null && parseInt(id, 10) > 0) {
		//$("bCancel").innerHTML =  DONE;
		jQuery(".bCancel").html(DONE);
		highlightsId = id;
		jQuery(".bDelete").removeClass("hidden");
		// showElement("bDelete");
		$("heading").innerHTML = "Edit Highlight";
		DWRHighlightManager.getHighlight(id, function (highlightsView) {
			if (highlightsView !== null) {
				showHighlights(highlightsView);
				isNew = false;
			}
		});
	} else {
		// since there is no id, we need to display Add screen.
		DWRHighlightManager.getMaxDisplayOrder(function (dispalyOrder) {
			if (dispalyOrder !== null) {
				DWRUtil.setValue("displayOrder", dispalyOrder);
			}
		});
		
		// select the default font sizes.
		DWRUtil.setValue("titleFontSize",  DEFAULT_TITLE_SIZE);
		DWRUtil.setValue("scrollingTextFontSize", DEFAULT_SCROLLING_TEXT_SIZE);
		
		// use the default font colors.
		DWRUtil.setValue("titleColor",  DEFAULT_TITLE_COLOR);
		DWRUtil.setValue("scrollingTextColor", DEFAULT_SCROLLING_TEXT_COLOR);		
		
		$("heading").innerHTML = "Add Highlight";
		isNew = true;
		jQuery(".bDelete").addClass("hidden");
		//$("bCancel").innerHTML = CANCEL;
		jQuery(".bCancel").html(CANCEL);
	}
}
/*
 * Save Highlights data
 */
function saveHighlights () {
	var id = DWRUtil.getValue("id");
	if (id !== null && id.length > 0) {
		isNew = false;
	} else {
		isNew = true;
	}

	// if the font size was not selected, then use default size.
	var titleFontSize = DWRUtil.getValue("titleFontSize");
	if (titleFontSize && titleFontSize == 'Select One') {
		titleFontSize = DEFAULT_TITLE_SIZE;
	}

	var scrollingTextSize = DWRUtil.getValue("scrollingTextFontSize");
	if (scrollingTextSize && scrollingTextSize == 'Select One') {
		scrollingTextSize = DEFAULT_SCROLLING_TEXT_SIZE;
	}

	DWRHighlightManager
	                .saveHighlight(
	                                DWRUtil.getValue("id"),
	                                DWRUtil.getValue("title"),
	                                DWRUtil.getValue("description"),
	                                DWRUtil.getValue("enabled"),
	                                DWRUtil.getValue("displayOrder"),
	                                titleFontSize,
	                                DWRUtil.getValue("titleColor"),
	                                DWRUtil.getValue("scrollingText"),
	                                scrollingTextSize,
	                                DWRUtil.getValue("scrollingTextColor"),
	                                function (highlightsView) {
		                                var message = Icon_Information;
		                                if (isNew) {
			                                message += formatMessage(HIGHLIGHT_ADDED,
			                                                [ highlightsView.title ]);
			                                // getHighlightsList(message);			                                
			                                isSaved = false;
			                                refreshFlexigridHighlights(message);
		                                } else {
			                                message += formatMessage(
			                                				HIGHLIGHT_UPDATED ,
			                                                [ highlightsView.title ]);
			                                showHighlights(highlightsView, message);
			                                isSaved = true;			                                
		                                }
		                                scrollTo(0, 0);
	                                });
}

/*
 * Validation code for highlights Form.
 */
function validateHighlightsForm () {
	if (bCancel === true) {
		return true;
	}
	// Put the HTML back into the text area
	myEditor.saveHTML();

	// The var html will now have the contents of the textarea
	var html = myEditor.get('element').value;

	// setting the editors content to the hidden field to save.
	var descHidden = $("description");
	descHidden.value = html;

	var title = $("title");
	var displayOrder = $("displayOrder");
	var description = $("description");
	var scrollingText = $("scrollingText");

	var errMsgs = [];

	if (title && isEmpty(title.value)) {
		errMsgs.push(formatMessage(ERRORS_REQUIRED, [HIGHLIGHT_TITLE_FIELD]));
	}

	if (scrollingText && isEmpty(scrollingText.value)) {
		errMsgs.push(formatMessage(ERRORS_REQUIRED, [HIGHLIGHT_SCROLLING_TEXT_FIELD]));
	} else if (scrollingText && scrollingText.value.length > 200) {
		errMsgs.push(HIGHLIGHT_SCROLLING_TEXT_ERROR);
	}

	if (displayOrder && isEmpty(displayOrder.value)) {
		errMsgs.push(formatMessage(ERRORS_REQUIRED, [HIGHLIGHT_DISPLAY_ORDER_FIELD]));
	} else if (isNaN(displayOrder.value)) {
		errMsgs.push(HIGHLIGHT_DISPLAY_ORDER_ERROR);
	} else if (parseInt(displayOrder.value) <= 0) {
		errMsgs.push(HIGHLIGHT_DISPLAY_ORDER_ERROR);
	}

	if (errMsgs.length > 0) {
		var errBuf = "Please verify the following:\n";
		for ( var i = 0; i < errMsgs.length; i++) {
			errBuf += " - " + errMsgs[i] + "\n";
		}
		alert(errBuf);
		return false;
	} else {
		saveHighlights();
		return true;
	}
}

/*
 * Delete the highlights
 */
function deleteHighlights () {
	if (confirm(HIGHLIGHT_DELETE_CONFIRM + "\n" + HIGHLIGHT_CLICK_OK)) {
    	if (highlightsId !== undefined) {
    		var title = $("title").value;
    		DWRHighlightManager.deleteHighlight(highlightsId, function () {
    			var message = Icon_Information;
    			message += formatMessage(HIGHLIGHT_DELETED, [ title ]);
    			// getHighlightsList(message);
    			refreshFlexigridHighlights(message);
    		});
    	}
	}
}
/*************End List*************************/
/*************Start Highlights news*************/
/*Example message arrays for the two demo scrollers*/
var pausecontent = [] ;
var pausecontentColor = [] ;

/*
 * Get the highlights news form the data base.
 */
function getHighlightsNews() {
	var height = 80/100 * (screen.height);
	var width = 60/100 *(screen.width);
	
	var userWidth = screen.availWidth;
    var userHeight = screen.availHeight;

    var leftPos;
    var topPos;
    
    leftPos = (userWidth - width) / 2,
    topPos = (userHeight - height) / 2;
    
    // contains the length of maximun characters that are allowed for description to display
    // and this value is based on the the current page from where we are viewing the highlights.
    var maxLength;
    // if the page value is true, then we are in home page.
    // else we are in services page.
    if (page) {
    	maxLength = 160;
    } else {
    	maxLength = 400;
    }

	DWRHighlightManager.getHighlightList("scroll", "displayOrder", "true", function (highlightsList) {
		if (highlightsList !== null && highlightsList.length > 0){
			 var content = "";
			 var scrollText = "";
			 for (var i = 0;i <  highlightsList.length; i++){
				if (parseInt((i % 2), 10) === 0){
					pausecontentColor[i] = "#6495ED";
				} else {
					pausecontentColor[i] = "#CDC9A5";
				}
				 content = "";
				 scrollText = "";
				 content += "<img src='"+domeListIcon+"' style='vertical-align: middle'/><span class='domeNews-heading' style='color: "+highlightsList[i].titleColor+"; font-size: "+highlightsList[i].titleFontSize+"px;'"; 
				 content += " onclick='createWindow(\"highlights/highlight.html?id="+highlightsList[i].id+"\",\"\","+leftPos+" , "+topPos+", "+width+", "+height+", null);'>";
				 content += highlightsList[i].title;
				 content +=  "</span><br />";
				 // if there is a specified text for scrolling the use that, else use description.
				 if (highlightsList[i].scrollingText !== null && highlightsList[i].scrollingText.length > 0) {
					 scrollText = highlightsList[i].scrollingText;
					 // in the case of home page, we need to truncate some text.
					 if (page && highlightsList[i].title.length + scrollText.length > maxLength) {
						 scrollText = getTruncateString(scrollText, maxLength - highlightsList[i].title.length);
					 }
					 content += "<span style='color: " +highlightsList[i].scrollingTextColor+"; font-size: "+ highlightsList[i].scrollingTextFontSize+"px;'>" + scrollText + "</span>";
					 
				 } else if (highlightsList[i].description !== null && highlightsList[i].description.length > 0) {
					var desc = highlightsList[i].description;
					if (desc.length + highlightsList[i].title.length > maxLength) {
						content += getTruncateString(desc, maxLength);
					} else {
						content += desc;
					}
				 }
				 content += " <span style='color: red;' >[<a href='javascript:void(0)' onclick='createWindow(\"highlights/highlight.html?id="+highlightsList[i].id+"\",\"\", "+leftPos+" , "+topPos+", "+width+", "+height+", null);'>...</a>]</span>";
			 	 pausecontent[i] = content;

			 }
		 } else if (highlightsList === null || highlightsList.length <= 0){
			 pausecontent[0] ="";
			 pausecontentColor[0] = "#6495ED";
			 pausecontent[1] = "";
			 pausecontentColor[1] = "#6495ED";
		 }	
		// name of message array, css_id, css_classname, pause;
		//new pausescroller(pausecontent, "domeNews", "domeNews", 8000, pausecontentColor, page);
		showNewsScrollText (pausecontent, pausecontentColor, page);		
	});	 
}

//To show which text can be scrolling text for news.
function showNewsScrollText(content,contentColor, isHomepage) {
	var newsContent = "<ul>";	
	for (var i = 0;i <  content.length; i++){
		var scrollMessage = "";
		var scrollMessage ='<li><div id="domeNews" class="" style="position: relative; overflow: hidden; text-align: top;';
		if (!isHomepage) {
			scrollMessage += 'width: 98%;'
		}	
		scrollMessage += '"><div class="innerDiv" style="position: absolute; width: 98%; color:'+contentColor[0]+'" id="domeNews'
		+ i+ '">'+ content[i]
		+ '</div><div class="innerDiv" style="position: absolute; width: 98%; visibility: hidden; color:';
		if (contentColor.length > 1) {
			scrollMessage += contentColor[i];
		} else {
			scrollMessage += contentColor[0];
		}	
		scrollMessage += '"" id="domeNews'+i+ '">';
		if (content.length > 1) {
			scrollMessage += content[i];
		} else {
			scrollMessage +=  content[0];
		}
		scrollMessage += '</div></div></li>';
		newsContent += scrollMessage;
	}
	newsContent += "</ul>";
	document.getElementById("domeNewsData").innerHTML = newsContent;
	getScrollNews();
}
//To get the scrolling news.
function getScrollNews() {
	jQuery(".jcarousellite").jCarouselLite({
		vertical: true,
		hoverPause:true,
		visible: 1,
		scroll: 1,
		auto:8000,
		pause: "#CarouselPlayPause",
		speed:1500,
		btnNext: "#next",
        btnPrev: "#prev"       
	});	
}
/*************End Highlights news*************/

/*
 * Return the formatted text that applies font color and size for the given text.
 */
function getFormattedText(text, fontSize, fontColor) {
	var formattedText = "";
	if (text && text != null && text.length > 0) {
		formattedText = "<span style=\'color: " + fontColor + "; font-size: " + fontSize + "px;'>" + text + "</span>";
	}
	
	return formattedText
}

/*
 * To show the preview of the text with the font size and color applied.
 * 
 * @param textType
 *          Indicates which text has been chaged. The value may be title or scrollingText.
 */
function showTextPreview(textType) {

	var text;
	var fontSize;
	var fontColor;
	var previewContent;
	
	// since the title text and attributes have been changes get that values and 
	// show the preview for that title.
	if (textType && textType.indexOf('title') > -1) {
		jQuery("#title_preview_fieldset").addClass("hidden");

		text = jQuery("#title").val();
		fontSize = jQuery("#titleFontSize").val();
		fontColor = jQuery("#titleColor").val();
		previewContent = getFormattedText(text, fontSize, fontColor);
		if (previewContent && previewContent.length > 0) {
			jQuery("#title_preview").html(previewContent);
			jQuery("#title_preview_fieldset").removeClass("hidden");
		}
	} else if (textType && textType.indexOf('scrollingText') > -1) {
		// showing preview for scrolling text.
		jQuery("#scrolling_text_preview_fieldset").addClass("hidden");

		text = jQuery("#scrollingText").val();
		fontSize = jQuery("#scrollingTextFontSize").val();
		fontColor = jQuery("#scrollingTextColor").val();
		previewContent = getFormattedText(text, fontSize, fontColor);
		if (previewContent && previewContent.length > 0) {
			jQuery("#scrolling_text_preview").html(previewContent);
			jQuery("#scrolling_text_preview_fieldset").removeClass("hidden");
		}
	}

}

//Link to get the highlight edit screen.
var highlightEditLink = '<a onclick="getHighlights({id});" href="javascript: void(0);"> Edit </a>';

/**
 * Method invoked by the FlexiGrid to get the data from DWR. 
 * @param grid the id of the grid
 * @param properties The properties of the grid
 * @return highlightsList
 */
function callDWR (grid, properties) {
	var sortColumnStr =properties.sortname;
	var sortOrderAscStr = (properties.sortorder === "asc");
	var startIndex = ((properties.newp - 1) *  properties.rp);
	var numResults = properties.rp;
	
	//Get the highlights data from DWR code.
	DWRHighlightManager.getHighlightsList(startIndex, numResults, sortColumnStr, sortOrderAscStr,
					function (data) {
		
		// Add the edit link into the cells data.
		if (data.rows !== null) {
            jQuery.each(data.rows, function (i, row) {
            	var link = highlightEditLink;
            	row.cell.push(link.replace(/{id}/, row.id));
            });
		}
        
        grid.addData(data);
    });
}

jQuery('b.top').click(
	function () {
		jQuery(this).parent().toggleClass('fh');
	}
);

/**
 * Resize the table width based on the selected columns.
 * @param columns
 * @return finalWidth
 */
function getGridWidth (columns) {
	var finalWidth = 'auto';
	var width = 0;
	jQuery.each(columns, function() {
		if (!this.hide) {
			width = width + this.width + 12;
		}
	});
	
	if (width > 0) {
		if (width > 1012) {
			finalWidth = 1012; 
		} else {
			finalWidth = width + 2;
		}		
	}
	return finalWidth;
}

//To get the highlights list using flexigrid.
function getHighlightsFlexiGrid() {
	var columns = [];
		columns = [{display: '#', name : 'rowCount', width : 30, sortable : false, align: 'center'},
		        	{display: 'Title', name : 'title', width : 410, sortable : false, align: 'left'},
		        	{display: 'Sort Order', name : 'displayOrder', width : 65, sortable : true, align: 'center'},
		        	{display: 'Visible', name : 'enabled', width : 55, sortable : true, align: 'center'},
		        	{display: 'Created On', name : 'createdOn', width : 150, sortable : true, align: 'center', hide: false},
		        	{display: 'Updated On', name : 'updatedOn', width : 150, sortable : true, align: 'center', hide: false},
		        	{display: 'Menu', name : 'view', width : 60, sortable : false, align: 'center'}
		        	];
		
	var width = getGridWidth (columns);
	highlightsFlexigrid = jQuery("#gridHighlightsList").flexigrid
    (
    {
    url: true,
    dataType: 'json',
    dwrData: true,
    colModel : columns,
    sortname: "displayOrder",
    sortorder: "asc",
    usepager: true,
    useRp: true,
    rp: NUM_RESULTS,
    showTableToggleBtn: false,
    height: "auto",
    width: width
    }
    );

	highlightsFlexigrid.each( function() {
    	gridObj = this.grid;
    });
}

//To refresh the highlights data and back to the list.
function refreshFlexigridHighlights(message) {
	//show the message
	if (message !== undefined && message.length > 0) {
		$("formSuccessMessages").innerHTML = message;
		showElement("formSuccessMessages");
	} else {
		hideElement("formSuccessMessages");
	}
	showElement("highlights_list");
	hideElement("highlights_edit");
	jQuery("#heading").html("Manage Highlights");

	if (!bCancel || isSaved) {
		// refresh the grid.
		if (gridObj !== null) {
			gridObj.populate();
		}
	}

}