/*******************************************************************
*
* Copyright (C) Transitor AB
*
* This source code is protected by copyright law and international
* treaties. Any unauthorised reproduction or distribution of this
* software in source or binary code form, or any part of it, is
* prohibited and may result in severe civil and criminal penalities,
* and will be prosecuted to the maximum extent possible under the
* law.
*
*******************************************************************/


function addOnLoad(theFunction)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function')
	{
		window.onload = theFunction;
	}
	else
	{
		window.onload = function() {
			if (oldonload)
			{
				oldonload();
			}
			theFunction();
		}
	}
}

function addOnUnLoad(theFunction)
{
	var oldonload = window.onunload;
	if (typeof window.onunload != 'function')
	{
		window.onunload = theFunction;
	}
	else
	{
		window.onunload = function() {
			if (oldonload)
			{
				oldonload();
			}
			theFunction();
		}
	}
}

/* Other onload function, but I believe the above one works on more browsers
function addOnLoad(theFunction)
{
	addEvent(window, 'load', theFunction);
}
*/
function addEvent(obj, eventType, theFunction)
{
	if (obj.addEventListener)
	{
		obj.addEventListener(eventType, theFunction, false);
		return true;
	}
	else if (obj.attachEvent)
	{
		var r = obj.attachEvent("on"+eventType, theFunction);
		return r;
	}
	else
	{
		return false;
	}
}

/**
* Function to create an overlib popup that is suitable to use for menu-like functions
*/
function showMenu(menuText)
{
/* WRAP is used, so then WIDTH is not used */
	return overlib(menuText,STICKY, TEXTSIZE,'10px', MOUSEOFF, WRAP, CELLPAD, 5, OFFSETX, 4, OFFSETY, 2);
}

function showMenuWidth(menuText, menuWidth)
{
/* WIDTH is specified so then WRAP is not used */
	return overlib(menuText,STICKY, WIDTH, menuWidth, TEXTSIZE,'10px', MOUSEOFF, CELLPAD, 5, OFFSETX, 4, OFFSETY, 2);
}

function showMessageWidth(menuText, menuWidth)
{
/* WIDTH is specified so then WRAP is not used */
	return overlib(menuText, WIDTH, menuWidth, TEXTSIZE,'10px', CELLPAD, 5, OFFSETX, 8, OFFSETY, 2, DELAY, 500);
}

function showMessageWidthAbove(menuText, menuWidth)
{
/* WIDTH is specified so then WRAP is not used */
	return overlib(menuText, ABOVE, WIDTH, menuWidth, TEXTSIZE,'10px', CELLPAD, 5, OFFSETX, 8, OFFSETY, 2, DELAY, 500);
}

/**
* Function to hide a menu. It just calls overlib with a suitable timeout for menues.
*/
function hideMenu()
{
	return nd(4000);
}

/**
* Check if the fieldElement contains a value. In that case set the
* targetElement to that value. Otherwise, set the targetElement to
* the value of the selectElement
*/
function setComboValue(targetElement, selectElement, fieldElement)
{
	var fieldValue = fieldElement.value;
	if (isEmpty(fieldValue))
		targetElement.value=selectElement.value;
	else
		targetElement.value=fieldValue;
}

/**
* Clear all fields of type text or textarea in the form
*/
function clearFormFields(theForm)
{
	for(var i=0; i < theForm.elements.length; i++)
	{
		if ((theForm.elements[i].type=='text') || (theForm.elements[i].type=='textarea'))
		{
			theForm.elements[i].value='';
		}
	}
}

/**
* Store the name and value in the session using an Ajax call
* Retrieve the value with prefix "ajaxpage." for example @ajaxpage.myvariable
*/
function storeAjaxSession(name, value)
{
	$j.post('gwt.logic.admin.AjaxSessionStore.action', {
		 name: name,
		 value: value
		});
}

/**
* Set the checked value of all fields of type checkbox in the form
*/
function setFormCheckBoxes(theForm, checkedValue)
{
	for(var i=0; i < theForm.elements.length; i++)
	{
		if (theForm.elements[i].type=='checkbox')
		{
			theForm.elements[i].checked=checkedValue;
		}
	}
}

/**
* Return true if at least one of the radio buttons in the group is checked
*/
function isOneChecked(radioGroup)
{
	if (radioGroup==null)
		return false;
	if (!radioGroup.length)
	{
		if (radioGroup.checked)
			return true;
		return false;
	}
	for(var i=0; i < radioGroup.length; i++)
	{
		if (radioGroup[i].checked)
			return true;
	}
	return false;
}

/**
* Return true if the input string is null or the empty string
*/
function isEmpty(inputStr)
{
	if (inputStr == "" || inputStr == null)
		return true	
	else
		return false
}

// Returns the string with all the beginning
// and ending whitespace removed
function trim(inputStr)
{
  return inputStr.replace(/^\s+/, '').replace(/\s+$/, '');
}

// Returns the left x characters of the string
function leftString(inputStr, count)
{
  if (inputStr.length>count) {
    return inputStr.substring(0, count);
  }
  else {
    return inputStr;
  }
}

// Returns the right x characters of the string
function rightString(inputStr, count)
{
  if (inputStr.length>count) {
    return inputStr.substring(inputStr.length-count, inputStr.length);
  }
  else {
    return inputStr;
  }
}

// Returns true if the string begins with value
function startsWith(inputStr, value)
{
  if (inputStr.length<value.length) {
    return false;
  }
  else {
    return inputStr.substring(0, value.length)===value;
  }
}

// Returns true if the string ends with value
function endsWith(inputStr, value)
{
	if (inputStr.length<value.length) {
    return false;
  }
  else {
    return inputStr.substring(inputStr.length-value.length, inputStr.length)===value;
  }
}

/**
* Delete the option that has the value val from the selector
*/
function deleteOption(selector, val) 
{ 
	for (i=0; i<selector.length; i++) 
	{ 
		if (selector.options[i].value==val) 
		{ 
			selector.options[i] = null; 
			break;
		} 
	} 
} 

/**
* Select the option that has the value val in the selector
*/
function selectOption(selector, val) 
{ 
	for (i=0; i<selector.length; i++) 
	{ 
		if (selector.options[i].value==val) 
		{ 
			selector.selectedIndex = i;
			break;
		} 
	} 
}

/**
* Set the linkURL to showpage... depending on the select box and field
*/
function setPageLinkURL()
{
	var pageLink = document.adminForm.pageLink;
	var pageParam = document.adminForm.pageParam;
	var otherLinkURL = document.adminForm.otherLinkURL;
	var linkURL = document.adminForm['info/linkURL'];
	if (!isEmpty(pageLink.value))
	{
		var pageURL = 'showpage.jsp?page_cd=' + pageLink.value;
		if (!isEmpty(pageParam.value))
		{
			if (pageParam.value.charAt(0)=='&')
			{
				pageURL += pageParam.value;
			}
			else
			{
				pageURL = pageURL + "&" + pageParam.value;
			}
		}
		linkURL.value = pageURL;
	}
	else
	{
		linkURL.value = otherLinkURL.value;
	}
}

function addI18n(defaultField)
{
	var timeInMillis = new Date().getTime();
	openTextWindow('gwt.logic.admin.AddI18nInfo!default.action?' + timeInMillis + '=1&editText=' + escape(defaultField.value),'reportWindow');
}

function editI18n(idField)
{
	var timeInMillis = new Date().getTime();
	openTextWindow('alias.logic.admin.GetI18nText.action?' + timeInMillis + '=1&orgInfo/info_id=' + idField.value,'reportWindow');
}

/**
* Open a window
*/
function openWindow(url, aName)
{
	winName = window.open(url, aName,'toolbar=yes,scrollbars=yes,resizable=yes,directories=no,menubar=no,width=600,height=500,top=50,left=50');
	winName.focus();
}

/**
* Open a window
*/
function openTextWindow(url, aName)
{
	winName = window.open(url, aName,'toolbar=yes,scrollbars=yes,resizable=yes,directories=no,menubar=no,width=500,height=300,top=50,left=50');
	winName.focus();
}
function openTextWindowWidthHeight(url, aName, width, height)
{
	winName = window.open(url, aName,'toolbar=yes,scrollbars=yes,resizable=yes,directories=no,menubar=no,width='+width+',height='+height+',top=50,left=50');
	winName.focus();
}


/**
* Open a window
*/
function openImageWindow(url, aName)
{
	winName = window.open(url, aName,'toolbar=yes,scrollbars=yes,resizable=yes,directories=no,menubar=no,width=600,height=500,top=50,left=50');
	winName.focus();
}

function imagePopup(action, info_id, country_cd, page_cd)
{
	var url = action + '?info_id=' + info_id + '&country_cd=' + country_cd + '&page_cd=' + page_cd;
	openTextWindow(url,'ImagePopup');
}
function imagePopupWidthHeight(action, info_id, country_cd, page_cd, width, height)
{
	var url = action + '?info_id=' + info_id + '&country_cd=' + country_cd + '&page_cd=' + page_cd;
	openTextWindowWidthHeight(url,'ImagePopup', width, height);
}

// get just the filename of a path
function getFileName(path) {
    return path.match(/[-_\w]+[.][\w]+$/i)[0];
}

function fileExists(path, errorFunction, successFunction)
{	
	$j.ajax({
		url: path,
		type:'HEAD',
		error: function(){errorFunction();},
		success: function(){successFunction();}
	});
}

// Observe! only works with adminForm, and imagehandling.jsp
// Also functions fileisnotthere and fileisthere must be defined!
function checkOverwriteImage(org_cd, lang_cd)
{
	// check if we're uploading an image and warn for overwriting
	if ($j('input[name=imageUpload]').val().length > 0){
		var basePath = 'org/' + org_cd + '/images/';
		if ($j('input[name=info/localised]:checked').length)
			basePath += lang_cd + '/';
		var imageURL = '';
		if ($j('input[name=info/imageURL]').val() != "")
		{
			imageURL = $j('input[name=info/imageURL]').val();
		}
		else
		{
			imageURL = basePath + getFileName($j('input[name=imageUpload]').val());
		}		
		fileExists(imageURL, fileisnotthere, fileisthere);
	}
	else
	{
		document.adminForm.submit(); // nothing to upload, just submit form
	}
}
// for some reason we have an imagehandling2 with another infoobject :(
function checkOverwriteImage2(org_cd, lang_cd)
{
	// check if we're uploading an image and warn for overwriting
	if ($j('input[name=imageUpload]').val().length > 0){
		var basePath = 'org/' + org_cd + '/images/';
		if ($j('input[name=imageInfo/localised]:checked').length)
			basePath += lang_cd + '/';
		var imageURL = '';
		if ($j('input[name=imageInfo/imageURL]').val() != "")
		{
			imageURL = $j('input[name=imageInfo/imageURL]').val();
		}
		else
		{
			imageURL = basePath + getFileName($j('input[name=imageUpload]').val());
		}
		fileExists(imageURL, fileisnotthere, fileisthere);
	}
	else
	{
		document.adminForm.submit(); // nothing to upload, just submit form
	}
}
// and finally we create a more adjustable version
// supply empty strings for values not used
// still needs methods fileisnotthere & fileisthere to be available in scope
function checkOverwriteImageAdjustable(org_cd, lang_cd, uploadField, urlField)
{
	if ($j('input[name=' + uploadField + ']').val().length > 0)
	{
		var imageURL;
		if (urlField != "" && $j('input[name=' + urlField + ']').val() != "")
		{
			imageURL = $j('input[name=' + urlField + ']').val();
		}
		else
		{
			var basePath = 'org/' + org_cd + '/images/';
			if (lang_cd != "")
				basePath += lang_cd + "/";
			imageURL = basePath + getFileName($j('input[name=' + uploadField + ']').val());
		}
		fileExists(imageURL, fileisnotthere, fileisthere)
	}
	else
	{
		document.adminForm.submit();
	}
}

function getAjaxStateClassName(theElement)
{
	var arrayOfClasses = theElement.className.split(' ');
	var theClass;
	for(var i = 0; arrayOfClasses.length > i; i++){
		theClass = arrayOfClasses[i];
		/* The classname should begin with expandState_  the rest of the name is the unique variable that
		should be sent with the Ajax request */
		if (theClass.substr(0,12)=="expandState_")
		{
			return theClass.substr(12);
		}
	}
	return null;
}

function contentChildToggle(pushed, options)
{ /* options are not used */
/* DZ 090615 The pushed variable is now the h2 element and not the img element anymore. */
	var expandImg;
	var tmpElem;
	for(var i = 0; pushed.childNodes.length > i; i++){
		tmpElem = pushed.childNodes[i];
		if (tmpElem.tagName=='IMG')
		{
			expandImg = tmpElem;
			break;
		}
	}
	/* Check if the element should generate an Ajax request */
	var ajaxStateName = getAjaxStateClassName(pushed);
	var elem = pushed.parentNode;
	var child;
	for(var i = 0; elem.childNodes.length > i; i++){
		child = elem.childNodes[i];
		if(child.className && child.className.substr(0,7) == "content"){
			if(child.style.display == "none"){
/*					$j(child).slideDown(300);   DZ 090420 Not using jquery at the moment because of flicker in IE */
				Effect.BlindDown(child,  { duration: 0.2});
				expandImg.src = 'sysimgs/is_minus.png';
				if (ajaxStateName != null)
					storeAjaxSession(ajaxStateName,'true');
/*					if (options && typeof (options.onShow) != undefined) options.onShow(); */
			}else{
/*					$j(child).slideUp(300);   DZ 090420 Not using jquery at the moment because of flicker in IE */
				Effect.BlindUp(child,  { duration: 0.2});
				expandImg.src = 'sysimgs/is_plus.png';
				if (ajaxStateName != null)
					storeAjaxSession(ajaxStateName,'false');
/*					if (options && typeof (options.onHide) != undefined) options.onHide(); */
			}
			break;
		}
	}
}


