//Jesper - trim function that works the same way as the trim method in java.lang.String
function trim(s)
{
  var begin = 0;
  var end = s.length;

  //Remove leading white space
  while (begin < end && s.substring(begin, begin + 1) <= ' ')
  {
    begin++;
  }

  //Remove trailing white space
  while (begin < end && s.substring(end - 1, end) <= ' ')
  {
    end--;
  }

  return (begin > 0 || end < s.length) ? s.substring(begin, end) : s;
}

function search_check(frm) {
  var trimmed = trim(frm.term.value);
  if (trimmed.length < 1) {
    alert('Search term must be at least 1 character in length.');
    frm.term.value = trimmed;
    frm.term.focus();
    return false;
  }
  return true;
}

function NewNamedWindow(pageurl,winname,wide,tall,scroll) { 
	return window.open(pageurl,winname,"toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=" + scroll + ",resizable=0,width=" + wide + ",height=" + tall + ",left=25,top=25");
}

function doPreviewRingtone(contentId, categoryId) {
  if (!categoryId) {
    categoryId = '';
  }
	wnd = NewNamedWindow('content_preview.jsp?contentId=' + contentId + '&categoryId=' + categoryId,'PreviewPopupScroll','335','205','0');
	try { wnd.focus(); } catch (e) { }
}

function closePreviewAndChangeOpener(buttonId)
{
  window.close();
  opener.location.replace(document.getElementById(buttonId).getAttribute('href'));
}

function closePreviewAndSaveCallerGreeting()
{
	window.close();
	var form = opener.document.getElementById('frm_operator_prompt');
	var selectedIndex = window.document.greetingForm.greeting[0].checked ? 0 : 1;
	form.greeting[selectedIndex].checked = true;
	opener.document.getElementById('save-change').click();
}

function getXAxis() {
       var x = (screen.width)/2;
       return x;
}

function getYAxis() {
       var y = (screen.height)/2;
       return y;
}

function doOpenPopup(page, width, height) {
       wnd = NewNamedWindow(page,'popup', width, height,'0');
       var x = getXAxis() - (width/2);
       var y = getYAxis() - (height/2);
       try {
             wnd.focus();
             wnd.moveTo(x,y);
       } catch (e) { }
 }
 
function newwindow(url){
	window.open(url,'','');
}
 
 function confirmationPopup(formToSubmit, text)
{
	var val = confirm(text);
	if (val)
	{
		//document.getElementById(formToSubmit).submit();
		return true;
	}
	else
	{	
		return false;
	}
}

// Performs different assignment checks based on the form to submit.
// If there are one or more conflicts then a modal message is displayed to
// confirm the default action in all of them; otherwise the form is submitted.
function performAssignmentCheck(url, formToSubmit) 
{
	var form = document.getElementById(formToSubmit);
	var keysToDisplay = new Array();
	switch(formToSubmit) {
		case 'frm_edit_shuffle_all':
			if (hasScheduleConflict(form, /gat=/)) {
				keysToDisplay.push('replace_group_tone_assignment_confirmation');
			}
		case 'frm_edit_callers_for_tone':
			if (hasScheduleConflict(form, /cat=/)) {
				keysToDisplay.push('replace_tone_assignment_confirmation');
			}
			break;
		case 'frm_edit_groups_for_tone':
			if (hasScheduleConflict(form, /gat=/)) {
				keysToDisplay.push('replace_group_tone_assignment_confirmation');
			}
			break;
		case 'frm_caller_edit':
			if (form.contactHasProfilesAssigned && !(form.group[0] == undefined || form.group[0].checked) && hasCheckboxSelected(form, '')) {
				keysToDisplay.push('add_new_group_to_caller_confirmation');
			}
			break;
		case 'frm_group_edit':
		case 'frm_add_new_group_to_tone':
		case 'frm_add_new_group_to_shuffle':
			if (hasCheckboxSelected(form, 'pro')) {
				keysToDisplay.push('add_new_group_to_caller_confirmation');
			}
			if (hasCheckboxSelected(form, 'grp')) {
				keysToDisplay.push('add_new_group_to_tone_confirmation');
			}
			break;
	}
	if (keysToDisplay.length > 0) {
		var fullUrl = url + '?';
		for (var i = 0; i < keysToDisplay.length; i++) {
			fullUrl = fullUrl + 'key=' + keysToDisplay[i] + '&';
		}
		fullUrl = fullUrl + 'form=' + formToSubmit;
		displayMessage(fullUrl);
	} else {
		form.submit();
	}
}

// Returns true if at least one of the checkboxes in the given form is checked.
// If a flag ID is specified then the checkbox ID has to match it in addition to being checked.
function hasCheckboxSelected(form, flagId)
{
	var elements = form.elements;
	var selected = false;
	for (var i = 0; !selected && i < elements.length; i++) {
		if (elements[i].type == "checkbox" && elements[i].checked) {
			selected = (!flagId || (elements[i].id == flagId))
		}
	}
	return selected;
}

// Returns true if there's at least one schedule conflict in the given form.
// A conflict is detected when there's a checked checkbox whose id contains the
// assigned time flag and its value overlaps with the corresponding selected time.
function hasScheduleConflict(form, assignedTimeFlag)
{
	var elements = form.elements;
	var conflict = false;
	for (var i = 0; !conflict && i < elements.length; i++) {
		if (elements[i].type == "checkbox" && elements[i].checked && elements[i].id.search(assignedTimeFlag) > 0) {
			var selectObject = document.getElementById("se_" + elements[i].id);
			var selectedTime = selectObject.options[selectObject.selectedIndex].value;
			var assignedTime = elements[i].id.split(assignedTimeFlag)[1];
			conflict = (assignedTime == 1 || selectedTime == 1 || assignedTime == selectedTime);
		}
	}
	return conflict;
}

function clickElementOnEnterKeyPress(event, elementId)
{	
	if (navigator.appName!="Netscape"){
		var keyCode = event ? (event.which ? event.which : event.keyCode) : event.keyCode;
	    if (keyCode == 13)
	    {
			clickElement(elementId);
			return false;
	    }
    }
    return true;
}

function clickElement(elementId)
{
	document.getElementById(elementId).click();
}
		
function displayMessage(url)
{
	messageObj.setSource(url);
	messageObj.setCssClassMessageBox(false);
	messageObj.setSize(400,200);
	messageObj.setShadowDivVisible(true);	// Enable shadow for these boxes
	messageObj.display();
}

function displayStaticMessage(messageContent,cssClass)
{
	messageObj.setHtmlContent(messageContent);
	messageObj.setSize(300,150);
	messageObj.setCssClassMessageBox(cssClass);
	messageObj.setSource(false);	// no html source since we want to use a static message here.
	messageObj.setShadowDivVisible(false);	// Disable shadow for these boxes	
	messageObj.display();
}

function closeMessage()
{
	messageObj.close();	
}

function truncateWords(string, wordLength)
{
	var truncatedString = "";
	var words = string.split(" ");
	for (var i = 0; i < words.length; i++)
	{
		truncatedString += words[i].truncate(wordLength) + " ";
	};
	return truncatedString.substring(0, truncatedString.length - 1);
}

/**
 * This function does string truncation in an unusual fashion. If the input string
 * is longer than the word length, it is truncated at the word length, not three
 * characters earlier.  The upshot of this is that truncated strings will actually
 * be 3 characters longer than the word length due to the &QUOT;...&QUOT;.
 *
 * @param  the input string
 * @param  given maximum word length
 * @return the truncated string.
 */
function truncateString(string, wordLength)
{
        var truncatedString = string;
        if (string != null && string.length > wordLength)
        {
                truncatedString = string.substring(0, wordLength) + "...";
        }
        return truncatedString;
}

