/**
	* @author Kevin Ross
	* @fileoverview Common functions used in app
*/

//config vars
var BBGRP_BASE_URL = "/bbsco/"
var BBGRP_ROOT_PATH = ""
var BBGRP_APP_CODE = 'bbsco'
var BBGRP_CRM_TITLE = 'BBGRP CRM 1.0 (bbsco)'
var BBGRP_CRM_BUSY_MSG_5 = ' - Loading, please wait...'
var BBGRP_ERR_1009_DESC = "An error has occurred whilst retrieving the data"
var BBGRP_ERR_1026_DESC = "An error has occured, we are unable to update region"
var BBGRP_ERR_1029_DESC = "An error has occured, we are unable to update days"

//window funcs

/**
*	Open new window based on param settings
* @param {string} pageurl Url of the page to open within the window
* @param {string} winname Window name
* @param {int} w Width
* @param {int} h Height
* @param {string} scroll Show browser scrolling bars y/n
* @param {string} menu Show browser menu bar y/n
* @param {string} location Show browser location field y/n 
* @return {window object} Window object
*/
function openWin(pageurl,winname,w,h,scroll,menu,location)
{
	var win;
  var winl = (screen.width-w)/2;
  var wint = (screen.height-h)/2;
  var settings  ='height='+h+',';
      settings +='width='+w+',';
      settings +='top='+wint+',';
      settings +='left='+winl+',';
      settings +='scrollbars='+scroll+',';
			settings +='menubar='+menu+',';
			settings +='location='+location+',';
      settings +='resizable=yes,status';
  win=window.open(pageurl,winname,settings);
  if(parseInt(navigator.appVersion) >= 4){win.window.focus();}
  return win;
}

/**
*	Open new window full screen
* @param {string} pageurl Url of the page to open within the window
* @param {string} winname Window name
* @return {window object} Window object
*/
function openWinFullScreen(pageurl,winname)
{
	var win = 0;
  w = screen.availWidth-10;
  h = screen.availHeight-20;
	features = 'width='+w+',height='+h;
  features += ',left=0,top=0,screenX=0,screenY=0';
	features += ',scrollbars';
  winfs = window.open(pageurl, winname, features);
	if(parseInt(navigator.appVersion) >= 4){winfs.window.focus();}
	return win;
}

//string funcs

/**
*	Removes extra blank spaces on the left side of a string
* @param {string} str String value
* @return {string} s New string value
*/
function LTrim(str)
{
	var whitespace = new String(" \t\n\r");
	var s = new String(str);

    if (whitespace.indexOf(s.charAt(0)) != -1) {
    	// We have a string with leading blank(s)...
		var j=0, i = s.length;

        // Iterate from the far left of string until we
        // don't have any more whitespace...
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
        	j++;

            // Get the substring from the first non-whitespace
           	// character to the end of the string...
            s = s.substring(j, i);
 	}

    return s;
}

/**
*	Removes extra blank spaces on the right side of a string
* @param {string} str String value
* @return {string} s New string value
*/
function RTrim(str)
{
	// We don't want to trim JUST spaces, but also tabs,
   	// line feeds, etc.  Add anything else you want to
    // "trim" here in Whitespace
   	var whitespace = new String(" \t\n\r");
	var s = new String(str);

    if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
    	// We have a string with trailing blank(s)...
		var i = s.length - 1;       // Get length of string

        // Iterate from the far right of string until we
       	// don't have any more whitespace...
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
        	i--;

			// Get the substring from the front of the string to
            // where the last non-whitespace character is...
           	s = s.substring(0, i+1);
    }

    return s;
}

/**
*	Removes extra blank spaces on the both sides of a string
* @param {string} str String value
* @return {string} s New string value
*/
function Trim(str)
{
	return RTrim(LTrim(str));
}

//cookie funcs

/**
*	Read cookie
* @param {string} name Cookie name
* @return {string} Cookie value
*/
function readCookie(name)
{
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0)
  { 
    offset = document.cookie.indexOf(search);
    if (offset != -1)
    { 
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}

/**
*	Write cookie
* @param {string} name Cookie name
* @param {string} value Cookie value
* @param {string} hours No of hours to expire in
* @param {string} path Cookie path
*/
function writeCookie(name, value, hours, path)
{
  var expire = "";
	var path = ";path="+path;
	
  if((hours != null) || (hours !=0))
  {
		if(hours >= 1)
    {	
			expire = new Date((new Date()).getTime() + hours * 3600000);
    	expire = "; expires=" + expire.toGMTString();
  	}
		else
		{
			expire = new Date((new Date()).getTime() - 48 * 60 * 60 * 1000);
    	expire = "; expires=" + expire.toGMTString();	
		}
	}
	
  document.cookie = name + "=" + escape(value) + expire + path;
}

//image funcs

/**
*	Preload images
*/
function preloadImages()
{ 
  var args = preloadImages.arguments;
  document.imageArray = new Array(args.length);
  for(var i=0; i<args.length; i++)
  {
    document.imageArray[i] = new Image;
    document.imageArray[i].src = args[i];
  }
}

/**
*	Switch Image
* @param {string} imgName Image name
* @param {string} imgSrc Image source
*/
function switchImage(imgName, imgSrc) 
{
  if (document.images)
  {
    if (imgSrc != "none")
    {
      document.images[imgName].src = imgSrc;
    }
  }
}

//list box funcs

/**
*	Remove all options from a list box
* @param {string} p_strFormName Form name
* @param {string} p_strListNamelue Listbox name
*/
function removeAllOptions(p_strFormName,p_strListName)
{
	var objList = document.forms[p_strFormName].elements[p_strListName]; 
	
	for(var i=(objList.options.length-1);i>=0;i--)	
	{
		objList.options[i] = null;
	}
	
	objList.selectedIndex = -1;
}

/**
*	Add new option to a list box
* @param {string} p_strFormName Form name
* @param {string} p_strListNamelue Listbox name
* @param {string} p_strOptionText Option text
* @param {string} p_strOptionValue Option value
*/
function addNewOption(p_strFormName,p_strListName,p_strOptionText,p_strOptionValue)
{
	var objList = document.forms[p_strFormName].elements[p_strListName]; 
	var objElem = document.createElement("OPTION");
	objElem.text = p_strOptionText;
	objElem.value = p_strOptionValue;
	objList.options.add(objElem,0);
	objList.options[0].selected = true;
}

/**
*	Clear dynamically populated form
* @param {string} p_strFormName Form name
*/
function clearForm(p_strFormName)
{
	//clear text fields
	var objElems = document.forms[p_strFormName].getElementsByTagName("input")
	for(var i=0;i<objElems.length;i++)
	{
		if (objElems[i].type=="text"){objElems[i].value=""}
	}
	
	//clear textareas
	var objElems = document.forms[p_strFormName].getElementsByTagName("textarea")
	for(var i=0;i<objElems.length;i++)
	{
		objElems[i].value=""
	}
}

/**
*	Get checked value from radio group
* @param {object} p_obj Radio group object
* @return {string} Checked value from radio group
*/
function getCheckedRadioGrpValue(p_obj)
{
	for(var i=0;i<p_obj.length;i++)
	{
		if(p_obj[i].checked)
		{
			return p_obj[i].value;
		}
	}
}


//App specific funcs

/**
*	Show confirmation msg box for selected records to be deleted
* @param {string} p_strForm Form name
* @param {string} p_strPostUrl Url we are posting form to
*/
function deleteSelectedRecs(p_strForm,p_strPostUrl){
	var blIsRecsToDelete
	var objForm = document.forms[p_strForm]

	if (confirm("Are you sure you wish to delete selected records?"))
	{
		try
		{
			//are there any records to delete	
			for (i=0;i<objForm.elements.length;i++)
			{
				if (objForm.elements[i].type=="checkbox")
				{
					if (objForm.elements[i].checked == true)
					{
						blIsRecsToDelete = true
					}
				}
			}
		}
		catch(e)
		{
			blIsRecsToDelete = false
		}
		
		if (blIsRecsToDelete)
		{
			objForm.action = p_strPostUrl
			objForm.submit()
			return true;
		}
		else
		{
			alert("There are no records to delete")
			return false;
		}
	}
}

/**
*	Toggle all checkboxes on/off for a given form
* @param {string} p_strForm Form name
*/
function toggleSelectAllRecs(p_strForm)
{
	var objForm = document.forms[p_strForm]
	//select all checkboxes	
		for (i=0;i<objForm.elements.length;i++)
		{
			if (objForm.elements[i].type=="checkbox")
			{
				//toggle
				if (objForm.elements[i].checked == false)
				{
					objForm.elements[i].checked = true
					objForm.chkToggleSelectAllRecs.checked = true
				}
				else
				{
					objForm.elements[i].checked = false
					objForm.chkToggleSelectAllRecs.checked = false	
				}
			}
		}
}

/**
*	Shows file upload progress window, used in conjunction with AspUpload
* @param {string} p_strPID AspUpload progress id
*/
function showUploadProgress(p_strPID)
{
	var strAppVersion = navigator.appVersion;
	
	if(strAppVersion.indexOf('MSIE') != -1 && strAppVersion.substr(strAppVersion.indexOf('MSIE')+5,1) > 4)
  {
		if (strAppVersion.indexOf("Macintosh") != -1 && strAppVersion.charAt(0) >= 3 )
    {
			
      window.open(BBGRP_BASE_URL+'shared/framebar.asp?to=10&PID='+p_strPID+'&b=NN','','width=370,height=115,status=no', true);
    }
    else
    {
  		var strWinStyle = "dialogWidth=385px; dialogHeight:140px; center:yes; status:no;";
    	window.showModelessDialog(BBGRP_BASE_URL+'shared/framebar.asp?to=10&PID='+p_strPID+'&b=IE',null,strWinStyle);
  	}
	}
  else
  {
  	window.open(BBGRP_BASE_URL+'shared/framebar.asp?to=10&PID='+p_strPID+'&b=NN','','width=370,height=115,status=no', true);
  }
 
}

/**
*	Get days in month from serverside script using ajax 
* @param {string} p_strFormName Form name
* @param {string} p_strListPrefix Listbox name
*/
function getDaysInMonth(p_strFormName,p_strListPrefix)
{
	var intMonthNum = document.getElementById(p_strListPrefix+"_Month").value;
	var intYearNum = document.getElementById(p_strListPrefix+"_Year").value;
	
	var kajax = new Kajax();
	kajax.url = BBGRP_BASE_URL+"shared/get_days_in_month.asp?monthNum="+intMonthNum+"&yearNum="+intYearNum;
	kajax.onCompletion = function(){updateDaysInMonth(p_strFormName,p_strListPrefix,kajax.response)};
	kajax.onError = function(){alert(BBGRP_ERR_1029_DESC)};
	kajax.sendRequest();
}

/**
*	Update days in month listbox with new values
* @param {string} p_strFormName Form name
* @param {string} p_strListPrefix Listbox name
* @param {string} p_intDaysInMonth No of days in month
*/
function updateDaysInMonth(p_strFormName,p_strListPrefix,p_intDaysInMonth)
{
	var intDaysInMonth = parseInt(p_intDaysInMonth)
	var objList = document.getElementById(p_strListPrefix+"_Day");
	
	if (!isNaN(intDaysInMonth))
	{
		removeAllOptions(p_strFormName,p_strListPrefix+"_Day");
		for(var i=0;i<intDaysInMonth;i++)
		{
			objList.options[i] = new Option(i+1,i+1);
		}
	}
}

/**
*	Load regions as xml from serverside script using ajax
* @param {string} p_strFormName Form name
* @param {string} p_strRegionListName Region listbox name
* @param {string} p_intCountyID County id
*/
function loadRegions(p_strFormName,p_strRegionListName,p_intCountyID)
{
	var kajax = new Kajax()
	kajax.url = BBGRP_BASE_URL+"shared/get_regions_as_xml.asp?countyid="+p_intCountyID
	kajax.responseType = "text/xml";
	kajax.onCompletion = function(){updateRegions(p_strFormName,p_strRegionListName,kajax.responseXML)};
	kajax.onError = function(){alert(BBGRP_ERR_1026_DESC)};
	kajax.sendRequest();
}

/**
*	Update region listbox with new values
* @param {string} p_strFormName Form name
* @param {string} p_strRegionListName Region listbox name
* @param {xml} p_objResponseXML XML object
*/
function updateRegions(p_strFormName,p_strRegionListName,p_objResponseXML)
{
	removeAllOptions(p_strFormName,p_strRegionListName);
		
	var objForm = document.forms[p_strFormName];
	var objList = objForm.elements[p_strRegionListName];
		
	var objRows = p_objResponseXML.getElementsByTagName("Row");
	for(var i=0;i<objRows.length;i++)
	{
		var objRow = objRows[i];
		var intRegionID = objRow.childNodes[0].childNodes[0].nodeValue;
		var strRegion = objRow.childNodes[1].childNodes[0].nodeValue;
		objList.options[i] = new Option(strRegion,intRegionID);
	}	
}

/**
*	Create uk date string from day,month and year listboxes and store in hidden field
* @param {string} p_strDateFieldName Date field name
*/
function convertDatePartsToDate(p_strDateFieldName)
{
	var objDate = document.getElementById(p_strDateFieldName);
	var strDate_Day = document.getElementById(p_strDateFieldName+"_Day").value;
	var strDate_Month = document.getElementById(p_strDateFieldName+"_Month").value;
	var strDate_Year = document.getElementById(p_strDateFieldName+"_Year").value;
	
	//pad day and month
	if (String(strDate_Day).length == 1){strDate_Day="0"+strDate_Day}
	if (String(strDate_Month).length == 1){strDate_Month="0"+strDate_Month}
	
	objDate.value = strDate_Day+"/"+strDate_Month+"/"+strDate_Year;
}

/**
*	Show loading icon animation telling user a task is in process
* @param {string} p_strMsgDiv Msg div name
* @param {string} p_strMsg Msg value
*/

function setBusyMsg(p_strMsgDiv,p_strMsg)
{
	var objMsgDiv = document.getElementById(p_strMsgDiv);
	var str = '<div style="position:absolute; left:30%; top:40%; background-color:white; layer-background-color:white; height:10%; width:15%;z-index:100">';
	var str = str + '<img src="'+BBGRP_BASE_URL+'images/loading_blue.gif" width="16" height="16">&nbsp;'
	var str = str + '<span style="font-family:verdana; font-size:11px;"><strong>'+p_strMsg+'</strong></span>'
	var str = str + '</div>'
	
	objMsgDiv.innerHTML = str
}

/**
*	Clear busy msg
* @param {string} p_strMsgDiv Msg div name
*/

function clearBusyMsg(p_strMsgDiv)
{
	var objMsgDiv = document.getElementById(p_strMsgDiv);
	objMsgDiv.innerHTML = "";
}
 