﻿// author: david leghorn
// description: universal collection of javascript functions utilised application wide


    var FailedValBg = "#c1e38e"; // invalid input controls will be highlighted with this background colour (functions utilising this variable are in validation.js or are declared inline on pages)
        

   // Opens iframe pop up style window by calling top window's ShowPopUp and passes url of page to be
   // displayed in pop up style window iframe. This function simply wraps the call to top window
   // ShowPopUp function - optionally, scripts could directly call top.ShowPopUp instead of this function if prefered  
   
   function OpenIframePopUp(pageUrl)
   {
        top.SetIframePopupTitle("Loading ...");
        top.ShowPopUp(pageUrl);
   }
   
   
   // Calculates available/visible page area size and assigns values to global variables. Typically scripts
   // requiring visible page area details will call this function and then utilise the global variables
   // varnames here! that it sets as required
   
    // CROSS BROWSER AVAILABLE DISPLAY AREA DETECTION (???? move to universal.js, or also define in universal.js ???)

    // Global variables holding browser window available width e.g. width is dependent on whether or not browser window
    // is maximised or tiled.
    // DisplayAreaWidth and DisplayAreaHeight global variables are populated via calls to 
    // GetAvailableDisplayArea() function. 
    // Sample Usage: If you require the current available display area - 1. call GetAvailableDisplayArea()
    // function (populates/sets global variables), 2. Retrieve available display area height and width from
    //  DisplayAreaWidth and DisplayAreaHeight global variables
    
    var DisplayAreaWidth;   
    var DisplayAreaHeight;

    // scripts requiring available display area should call this function and then read available area
    // values from DisplayAreaHeight and DisplayAreaWidth global variables (above)
    function GetAvailableDisplayArea()
    {
        if (document.documentElement && document.documentElement.clientHeight)  // Explorer 6 Strict Mode
        {
            DisplayAreaWidth = document.documentElement.clientWidth;
            DisplayAreaHeight = document.documentElement.clientHeight;
        }

        else if (self.innerHeight) // all except Explorer e.g. firefox, opera
        {
            DisplayAreaWidth = self.innerWidth;
            DisplayAreaHeight = self.innerHeight;
        }
        
        else if (document.body) // other Explorers
        {
    	    DisplayAreaWidth = document.body.clientWidth;
    	    DisplayAreaHeight = document.body.clientHeight;
        }
    }

   
    // extends javascripts built String class to include a Trim() method
    
    String.prototype.Trim = function() 
    {
        a = this.replace(/^\s+/, '');
        return a.replace(/\s+$/, '');
    };


    // Disable or Enable form control helper function
    // params:
    // formObjectId = the id attribute of the form element e.g. textbox or button's id
    // boolDisable = boolean indicating whether element should be disabled (true) or enabled (false)
    
    function DisableEnableFormElement(formObjectId, boolDisable)
    {
        document.getElementById(formObjectId).disabled = boolDisable;
    }
    
    
    // Displays or hides an object by changing objects display attribute
    // objid : id of object to be displayed or hidden
    // displayValue : display attribute value - "block" (show object) or "none" (hide object)
    
    function DisplayHideObj(objid,displayValue)
    {
        document.getElementById(objid).style.display = displayValue;
    }
    
    
    // Shows or Hides object by changing objects visibility attribute
    // objid : id of object to be hidden or visible
    // vis : visibility attribute value - "visible" or "hidden"
    
    function ShowHideObj(objid,vis)
    {
        document.getElementById(objid).style.visibility = vis;
    }

    
    function SetObjBgColour(objid,colour)
    {
        document.getElementById(objid).style.backgroundColor = colour;
    }
    
    function SetObjInnerHtml(objid,htmlStr)
    {
        document.getElementById(objid).innerHTML = htmlStr;
    }
    
    // Expands and collapses section wrapper divs (where div id = objid parameter)
    // objid : id of div tag to show/hide - expand/collapse
    // linkid : id of <a link tag that is clicked to toggle section expanded or collapsed
    
    // expands or collapses section via changing objects display: property to "block" or "none"
    // updates link (linkId) objects text to display message Expand or Collapse section as required
    
    function ExpandCollapseSection(objid,linkId)
    {
        var objRef = document.getElementById(objid);
        var state = objRef.style.display;
        var dis, toggleMsg;
        
        if( state == "block" )
        { dis = "none"; toggleMsg = "Expand Section"}
        else
        { dis = "block"; toggleMsg="Collapse Section";}
        
        objRef.style.display = dis
        document.getElementById(linkId).innerHTML = toggleMsg;
    }
        

    
    // added 20/08/07 
    // Horizontally centres div, top position is set (in pixels) by 2nd parameter
    
    function HorizontallyCenterDiv(divId,divWidth,divTop)
    {
        var divRef = document.getElementById(divId);
        var xpos,ypos;
        ypos = divTop + GetPageScrollYOffset();
        
        // width and height set so this function can be utilised in grow/shrink centered layer animations
        divRef.style.width = divWidth + 'px';
        divRef.style.top = ypos + 'px';
        
        GetAvailableDisplayArea();
        
        xpos = parseInt((DisplayAreaWidth - divWidth) / 2);
        
        if(xpos < 0 ) { xpos = 10; }
        
        // to do : account for scroll offsets ??
        
        divRef.style.left = xpos + 'px';
        divRef.style.visibility = "visible";
    }
    
    
    // Centre Div element on screen (horizontally and vertically)
    // explicitly sets div elements width and height so function may be used in animations
    
    function CenterDiv(divId, divWidth, divHeight)
    {
        var divRef = document.getElementById(divId);
        var xpos,ypos;
        
        // width and height set so this function can be utilised in grow/shrink centered layer animations
        divRef.style.width = divWidth + 'px';
        divRef.style.height = divHeight + 'px';
        
        GetAvailableDisplayArea();
        
        xpos = parseInt((DisplayAreaWidth - divWidth) / 2);
        ypos = parseInt((DisplayAreaHeight - divHeight) / 2);
        
        ypos += GetPageScrollYOffset();  // NEW SEP14
        
        if(xpos < 0 ) { xpos = 10; }
        if(ypos < 0 ) { ypos = 10; }
        
        
        var yoffset = GetPageScrollYOffset();
        
        divRef.style.left = xpos + 'px';
        divRef.style.top = ypos + 'px';
        
    }
    
   
   function GetPageScrollYOffset()    // NEW SEP14
   {
        var scrollOffsetY = 0; // default
        
        if( IsIE == true )
	    {
		    scrollOffsetY = document.documentElement.scrollTop;
	    }
	    else
	    {
		    scrollOffsetY = window.pageYOffset;
	    }
	    
	    return scrollOffsetY;
   }
    
    
   
var PopupYOffset = 20;
  
   
// SETS JOB DETAIL POPUPS Y CO-ORDINATE

function SetPopupYpos(popupDivId)
{
	var winY = 20;
	winY = GetYscrollOffset();

//	if( IsIE == true )
//	{
//		winY = document.documentElement.scrollTop;
//	}
//	else
//	{
//		winY = window.pageYOffset;
//	}

	//var yOffset = getTopOffset();

	yPos = winY + PopupYOffset;

	// update popup layer top pos
	document.getElementById(popupDivId).style.top = yPos+"px";
 
}


// GETS CURRENT PAGE Y SCROLL OFFSET 

function GetYscrollOffset()
{
	if( IsIE == true )
	{
		return document.documentElement.scrollTop;
	}
		
	else
	{
		return window.pageYOffset;
	}
}
    
    
    var CenteredDivId, CenteredDivIdObjectRef, CenteredDivTargetHeight, CenteredDivTargetWidth;
    var GrowRate = 1.35;
    var GrowAnimationCompletedCallbackFunction = null; // assigned as a pointer to a js function that should
                                                // be called when animation complete
                                                
   // var UseGrowCallbackHandler = false;
    
                                                
    function GrowCenteredDiv(div_Id, targetWidth, targetHeight, grow_rate, growCompletedCallbackHandler)
    {
        CenteredDivId = div_Id;
        CenteredDivObjectRef = document.getElementById(div_Id);
        CenteredDivTargetHeight = targetHeight;
        CenteredDivTargetWidth = targetWidth;
        GrowRate = grow_rate;
        // UseGrowCallbackHandler = usesCallbackHandler;
       GrowAnimationCompletedCallbackFunction = growCompletedCallbackHandler

        _animateGrowCenteredDiv();
    }
    

    function _animateGrowCenteredDiv()
    {
        var currentW = parseInt(CenteredDivObjectRef.style.width);
        var currentH = parseInt(CenteredDivObjectRef.style.height);

       // alert(currentW + " H = " + currentH + "\n\n Target Wid = " + CenteredDivTargetWidth + "\n\n Target Height = " + CenteredDivTargetHeight);
       
        var newHeight, newWidth;
        var continueAnimateH = false;
        var continueAnimateW = false;
        
        if( currentW != CenteredDivTargetWidth )
        {
            if( currentW < CenteredDivTargetWidth )
            {
                newWidth = currentW * GrowRate;
                if(newWidth >= CenteredDivTargetWidth)
                {
                    newWidth = CenteredDivTargetWidth;
                }
                //CenteredDivObjectRef.style.width = newWidth + 'px';
                continueAnimateW = true;
            }
            else if( currentW > CenteredDivTargetWidth )
            {
               // CenteredDivObjectRef.style.width = CenteredDivTargetWidth + 'px';
                continueAnimateW = false;
            }
        }
        else
        {
            newWidth = CenteredDivTargetWidth;
            continueAnimateW = false;
        }
        
        
        if( currentH != CenteredDivTargetHeight )
        {   
            if( currentH < CenteredDivTargetHeight )
            {
                newHeight = currentH * GrowRate;
                
                if(newHeight >= CenteredDivTargetHeight)
                {
                    newHeight = CenteredDivTargetHeight;
                }
                
               // CenteredDivObjectRef.style.height = newHeight + 'px';
                continueAnimateH = true;
            }
            else if( currentH > CenteredDivTargetHeight )
            {
              //  CenteredDivObjectRef.style.height = CenteredDivTargetHeight + 'px';
                continueAnimateH = false;
            }
        }
        else
        {
            newHeight = CenteredDivTargetHeight;
            continueAnimateH = false;
        }
        
        
        // CONTINUE ANIMATION ??
        
        if( continueAnimateH == true || continueAnimateW == true)
        {
            CenterDiv(CenteredDivId, newWidth, newHeight);
            // new 14/09 - set div top pos acconting for scroll offset
            //SetPopupYpos(CenteredDivId);
            setTimeout("_animateGrowCenteredDiv()",50);
        }
        else   // Animation done (optionally call animation complete callback handler)
        {
            if(GrowAnimationCompletedCallbackFunction != null)
            {
                // set overflow visible and height auto in case increased text size increased height 
                // beyond animation set height limit
                
//                if(IsIE == true)
//                {
//                  document.getElementById(CenteredDivId).style.overflow = 'auto';
//                  document.getElementById(CenteredDivId).style.height = 'auto';
//                }
                
                GrowAnimationCompletedCallbackFunction();
            }
//            else
//            {
//                alert("finished - NO CALLBACK HANDLER");
//            } 
        }
        
        
        // if page is not top level window page - forces page to top level window
        
        function SetAsTopLevelPage()
        {
            var thisPage = this.location.href;
            var topPage = top.location.href;
            if(thisPage != topPage) { top.location.href = thisPage; }
        }
     
    }
    
			
// ------------------ COOKIE FUNCTIONS 
//( based on code from http://www.echoecho.com/jscookies02.htm ?) ---------------------

function GetCookie(NameOfCookie)
{
if (document.cookie.length > 0) 
{ 
    begin = document.cookie.indexOf(NameOfCookie+"="); 
    if (begin != -1) // Note: != means "is not equal to"
    { 
        begin += NameOfCookie.length+1; 
        end = document.cookie.indexOf(";", begin);
        if (end == -1) end = document.cookie.length;
        return unescape(document.cookie.substring(begin, end)); } 
    }
    
return null; // cookie was not set
}


// SET COOKIE
// note: NO DATE SPECIFIED AS COOKIE SHOULD EXPIRE WHEN BROWSER WINDOW IS CLOSED!!

function SetCookie(NameOfCookie, value) 
{
	document.cookie = NameOfCookie + "=" + escape(value);
}


function SetCookieWithDate(NameOfCookie, value, expiredays) 
{
    // Three variables are used to set the new cookie. 
    // The name of the cookie, the value to be stored,
    // and finally the number of days until the cookie expires.
    // The first lines in the function convert 
    // the number of days to a valid date.

    var ExpireDate = new Date ();
    ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));

    // The next line stores the cookie, simply by assigning 
    // the values to the "document.cookie" object.
    // Note the date is converted to Greenwich Mean time using
    // the "toGMTstring()" function.

    document.cookie = NameOfCookie + "=" + escape(value) + 
    ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}



// ------------------- date format related ---------------------------

  // GET DATE IN UNIVERSAL FORMAT
    // Converts date from dd/mm/yyyy format to yyyy/mm/dd (universal format) for consistent date 
    // handling in Sql Server (irrespective of SqlServer instance's date settings)
    
    // identifies Uk formatted date (via regular expression) and converts to yyyy/mm/dd format
    // Note: if other date formats are utilised by production system - include reg expressions
    // to identify formats and convert them to universal format
    
    function GetUniversalFormatedDate(dateTxtBoxId)
    {
         var dateString = document.getElementById(dateTxtBoxId).value.Trim();
         var universalFormattedDate = "";
         var splitDateArray = dateString.split("/");
         var dd, mm, yyyy;
                    
         if(dateString != "")
         {
                // simple reg expression to check if in uk format (dd/mm/yyyy or d/m/yyyy) - note year
                // must contain 4 digits
                
                // matches 1 0r 2 digits followed by '/' followed by 1 or 2 digits, followed by '/'
                // followed by 4 digits
                var ukDateMatchRegex = new RegExp("^[0-9]{1,2}[/][0-9]{1,2}[/][0-9]{4}");
                
                // simple reg expression to match a date already in either universal format
                // yyyy/mm/dd or format yyyy/dd/mm
                var universalDateMatchRegex = new RegExp("^[0-9]{4}[/][0-9]{1,2}[/][0-9]{1,2}");
                
                // test for matches
                var ukDateFormatMatch = ukDateMatchRegex.test(dateString);
                var universalFormatMatch = universalDateMatchRegex.test(dateString);
                
              //  alert(dateTxtBoxId + " is uk format match = " + ukDateFormatMatch);
              //  alert(dateTxtBoxId + " is universal format match = " + universalFormatMatch);
                
                // if uk format - re assemble date in universal format yyyy/mm/dd
                if( ukDateFormatMatch == true )
                {
                    splitDateArray = dateString.split("/");
                     dd = splitDateArray[0];
                     mm = splitDateArray[1];
                     yyyy = splitDateArray[2];
                    universalFormattedDate = yyyy + "/" + mm + "/" + dd;
                }
                else if(universalFormatMatch == true)
                {
                    universalFormattedDate = dateString;
                    
                    // If potentially GoPlan will encounter dates in yyyy/dd/mm format, uncomment code
                    // below as can help identify the aforementioned format and re-assemble as universal date
                    
                    // split up date components and test if mm > 12, if so date is not currently
                    // universal but is in yyyy/
//                    splitDateArray = dateString.split("/");
//                     yyyy = splitDateArray[0];
//                     mm, = splitDateArray[1];
//                     dd = splitDateArray[2];
//                     
//                     // if universal month > 12 then date is formatted as yyyy/dd/mm 
//                     if(Number(mm) > 12) { dd = splitDateArray[1]; mm, = splitDateArray[2]; }
//                     universalFormattedDate = yyyy + "/" + mm + "/" + dd;
                }
                else
                {
                    alert("Date format not identified by current code - GetUniversalFormatedDate function in Scripts/addEditDeletePageUtilities.js needs extended to accomodate dates in format " + dateString);
                }
                
                // TEST FOR OTHER DATE FORMATS HERE IF REQUIRED
                
         }
         
        // alert("universalFormattedDate = " + universalFormattedDate);
         
         return universalFormattedDate;
    }


    // =================== GET CONTROL VALUE  ==========================
    
    // returns value from passed input control id
    // typically this function is utilised to read values from form input controls when assembling parameters
    // to be passed to update or insert code behind PageMethods / Web Method calls
    
    function GetControlValue(controlId)
    {
        var controlObjectRef = document.getElementById(controlId);
        
        // TEST
       // alert("object type = " + controlObjectRef.type );
        
        if( controlObjectRef.type == "text" || controlObjectRef.type == "textarea")    // textbox - <input type="text"
        {
            // TEST
           // alert("value from textbox id = " + controlId + " = " + controlObjectRef.value.Trim());
            return controlObjectRef.value.Trim();
        }
        
        else if (controlObjectRef.type == "select-one")     // LIST CONTROL <select> element
        {
            var listIndex = controlObjectRef.selectedIndex;
            var listValue = controlObjectRef.options[listIndex].value;
            
            // TEST
            //alert("value from list id = " + controlId + " = " + listValue);
            
            return listValue;
        }
        
        else if( controlObjectRef.type == "checkbox")     // <input type="checkbox" 
        {
            // TEST
            //alert("value from checkbox id = " + controlId + " = " + controlObjectRef.checked);
            if( controlObjectRef.checked == true )
            {
                return 1;
            }
            else
            {
                return 0;
            }
           // return controlObjectRef.checked;
        }
        
    }
    
    
    // DISABLE/ENABLE HTML Element
    
    function EnableDisableObj(objId,boolDisable)
    {
        document.getElementById(objId).disabled = boolDisable;
    }
    
    

// ---------------------- OPACITY FADE IN /FADE OUT EFFECTS ------------------------------

    // could extend with more conditional comments to check version of IE is capable
    // of running this code. For now try catch will gracefully handle incapable browsers
    
    var CurrentAnimationOpacity = 0;
    var OpacityIncrement = 5;
    var AnimationEndOpacity = 100;
    var FadeObjectId;
    
    // fadeOut param = boolean indicating if fade in or fade out animation to be run
    function FadeOpacity(divId,startOpacity,finalOpacity,increment,fadeOut)
    {
        CurrentAnimationOpacity = startOpacity;
        AnimationEndOpacity = finalOpacity;
        OpacityIncrement = increment;
        FadeObjectId = divId;
        
        if(fadeOut == true)
        {
            FadeOutDiv();
        }
        else   // fade in
        {
            if( document.getElementById(divId).style.visibility == "hidden")
            {
                ShowHideObj(objId,"visible");
            }
            FadeInDiv();
        }
    }

    
    function FadeInDiv()
    {
            //alert("fade in called, opacity = " + CurrentAnimationOpacity);
        CurrentAnimationOpacity += OpacityIncrement;
        var divRef = document.getElementById(FadeObjectId);
        
        try
        {
            if(CurrentAnimationOpacity >= AnimationEndOpacity)
            {
                CurrentAnimationOpacity = AnimationEndOpacity;
                
                if(IsIE == true)
                {
                    //divRef.filters.alpha.opacity  = CurrentAnimationOpacity;
                    divRef.style.filter="alpha(opacity="+ CurrentAnimationOpacity +")";
                }
                else
                {
                    divRef.style.MozOpacity = CurrentAnimationOpacity/100;
                } 
                
//                if(AnimationEndOpacity == 0)
//                {
//                    ShowHideObj(FadeObjectId,"hidden");
//                }
            }
            else
            {        
                if(IsIE == true)
                {
                  //  divRef.filters.alpha.opacity  = CurrentAnimationOpacity;
                  divRef.style.filter="alpha(opacity="+ CurrentAnimationOpacity +")";
                }
                else
                {
                    divRef.style.MozOpacity = CurrentAnimationOpacity/100;
                } 
                
                setTimeout("FadeInDiv()",50);
            }
        }
        catch(error)
        {
        //alert("ERR = " + error);
        }
    }
    
        
    function FadeOutDiv()
    {
        //alert("fade out called, opacity = " + CurrentAnimationOpacity);
        CurrentAnimationOpacity -= OpacityIncrement;
        var divRef = document.getElementById(FadeObjectId);
        
        try
        {
            if(CurrentAnimationOpacity <= AnimationEndOpacity)
            {
                CurrentAnimationOpacity = AnimationEndOpacity;
                if(IsIE == true)
                {
                    //divRef.filters.alpha.opacity  = CurrentAnimationOpacity;
                    divRef.style.filter="alpha(opacity="+ CurrentAnimationOpacity +")";
                }
                else
                {
                    divRef.style.MozOpacity = CurrentAnimationOpacity/100;
                } 
                
                ShowHideObj(FadeObjectId,"hidden");
               // alert("fade out done!!");
            }
            else
            {
                if(IsIE == true)
                {
                    //divRef.filters.alpha.opacity  = CurrentAnimationOpacity;
                    divRef.style.filter="alpha(opacity="+ CurrentAnimationOpacity +")";
                }
                else
                {
                    divRef.style.MozOpacity = CurrentAnimationOpacity/100;
                } 
                 setTimeout("FadeOutDiv()",50);
            }
        }
        catch(error)
        {
        }
    }
    
    
    function SetObjectOpacity(divId,opacityValue)
    {
        try
        {
            if(IsIE == true)
            {
                //divRef.filters.alpha.opacity  = CurrentAnimationOpacity;
                document.getElementById(divId).style.filter="alpha(opacity="+ opacityValue +")";
            }
            else
            {
                document.getElementById(divId).style.MozOpacity = opacityValue/100;
            } 
         }
         catch(er) {}
    }
    
    
    // returns string of comma seperated selected list values
    function GetListSelectedValues(listId)
    {
        var listref = document.getElementById(listId);
        var selectedValues = "";
        var value;
        
        for(i=0; i < listref.length; i++)
        {
            if( listref.options[i].selected == true )
            {
                if(selectedValues == "")
                {
                    selectedValues += listref.options[i].value;
                }
                else
                {
                   selectedValues += ","+listref.options[i].value;
                }
            }
         }
         
         return selectedValues;
    }
    
    
    // displays (or hides) validation div and sets control bg colour
    // validationMsgId = id of the validation message wrapper
    // displayType = "block" || "inline"
    // controlId = id of the input control we are validating
    // bgColour = set controls background colour to bgColour
    
    function DisplayHideValidationMessage(validationMsgId,displayType,controlId,bgColour)
    {
        document.getElementById(validationMsgId).style.display = displayType;
            document.getElementById(controlId).style.backgroundColor = bgColour;
    }
    
    
    // -------- site serach related -----------
    
    function btn_SearchSiteClick()
    {
        var words = document.getElementById("txtSiteSearch").value.Trim();
        if(words == "")
        {
            alert("Please enter your search keywords");
        }
        else
        {
            top.location.href = "http://ifa-voice.com/SiteSearch.aspx?keywords=" + words;
        }
    }
    
    
		// submits site search if user presses return key

		function CheckForSearchBoxReturnKeyPress( e )
		{
			if ( window.event ) 
			{
				if( event.keyCode == 13 )
				{
					btn_SearchSiteClick();
					return false;
				}
			}

			else
			{
				if( e.keyCode == 13 )   // return key press
				{
					btn_SearchSiteClick();
					return false;
				}
			}
		}
		
		
// code to hide drop lists in ie 6 when displaying popup divs
		
var PageListIdsArray = new Array(); // array to be defined inline in page js

function ShowHidePageLists(vis)
{
    for(i=0; i < PageListIdsArray.length; i++)
    {
        document.getElementById(PageListIdsArray[i]).style.visibility = vis;
    }
}



function ValidateRadioButtonListSelectionMade(radioButtonListId)
{
    var listItemArray = document.getElementsByName(radioButtonListId);
    var isValid = false;

    for (var i=0; i< listItemArray.length; i++)
    {
        var listItem = listItemArray[i];

        if ( listItem.checked )
        {
            isValid = true;
        }
    }

    return isValid ;
}


function PrintPage()
{
    window.print();  
}