//==============================================================
// Check date legal (input: int values)
//==============================================================
function dateValid(dd,mm,yyyy)
{
    // General validity
    if (dd == 0 || mm == 0 || yyyy == 0)
        return false;
    // On feb - check if the year %% 4 == 0
    else if (mm == 2 && (dd > ((yyyy % 4 == 0) ? 29 : 28) ))
        return false;
    // Check for number of days in the month - such as 31/11 is illegal
    else if ( (mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd > 30)
        return false;
    else
        return true;
}
                
//==============================================================
// Max string length limiter
//==============================================================
function limitStringLength(objTextElement,intLen,evt)
{
    var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : window.event.keyCode;

    if (keyCode == 8 || keyCode == 46 ||          // 8=BKSP, 46=DEL, 
        keyCode == 9)                             // Tab
    {
        return true;
    }
    if (objTextElement.value.length >= intLen)
    {
        return false;
    }
}

//==============================================================
// Checks that a text box contains numeric value
//==============================================================
function maskNumeric(evt)
{
    var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : window.event.keyCode;

    if ( (keyCode >= 48 && keyCode <= 57) ||      // regular numbers
         (keyCode >= 96 && keyCode <= 105) ||     // Num area numbers
         keyCode == 8 || keyCode == 46 ||         // 8=BKSP, 46=DEL, 
         keyCode == 9)                                         // Tab
    {
        return true;
    }
    else
    {
        return false;
    }
}

//==============================================================
// Mask space and other restricted keys
//==============================================================
function maskLiteral(evt)
{
    var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : window.event.keyCode;

    if (keyCode == 32 ||                                   // Space
        keyCode == 34  || keyCode == 39  ||   // [',""]
        keyCode == 91  || keyCode == 93  ||   // [,]
        keyCode == 60  || keyCode == 62  ||   // <,>
        keyCode == 38)                                     // &        
    {
        return false;
    }
}

//==============================================================
// Mask restricted keys. space allowed
//==============================================================
function maskFreeText(evt)
{
    var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : window.event.keyCode;

    if (keyCode == 91  || keyCode == 93  ||   // [,]
        keyCode == 60  || keyCode == 62  ||   // <,>
        keyCode == 38)                                     // &        
    {
        return false;
    }
}

//==============================================================
// Creates an AJAX request and returns a response
//==============================================================
function doAjaxRequest(strURL,strRequest)
{
    var xmlhttp             = false;

    //==============================================================
    // Using try/catch mechanism to create the appropriate
    // XMLHTTP object based on browser's capabilities
    //==============================================================
    //IE
    try 
        {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
    catch (e) 
        {  
            try 
                {
                    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                } 
            catch (E) 
            {
                xmlhttp = false;
            }
        }

    //Other browsers
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
    {
    try 
        {
            xmlhttp = new XMLHttpRequest();
        } 
    catch (e) 
        {
            xmlhttp=false;
        }
    }

    if (!xmlhttp && window.createRequest) 
    {
        try 
        {
            xmlhttp = window.createRequest();
        } 
        catch (e) 
        {
            xmlhttp=false;
        }
    }

    //==============================================================
    // Prepare the AJAX post to the server
    //==============================================================
    if (xmlhttp)
    {
        xmlhttp.open("POST",strURL,false);
                        
        xmlhttp.setRequestHeader("Content-Type", "text/xml");

        xmlhttp.send(strRequest);
        if (xmlhttp.readyState==4)
        {
            // if "OK"
            if (xmlhttp.status==200)
            {
                return xmlhttp.responseText;
            }
            else
            {
                //alert("Message 100: Problem retrieving data. status: " + xmlhttp.status); // Problem retrieving XML data
                alert("Message 100: Error " + xmlhttp.status + ": unable to send AJAX call to: " + strURL + "\n" + " XML: " + strRequest);
                return null;
            }
        }
        else
        {
            alert("Message 101: AJAX call returned a readystate: " + xmlhttp.readyState + " with status: " + xmlhttp.status); // Problem retrieving XML data
            return null;
        }
    }
    else
    {
        alert("Message 102: Your browser does not support AJAX calls."); // Your browser does not support XMLHTTP
        return null;
    }
}

//==============================================================
// Loads a response XML on the client side to an XML object
//==============================================================
function loadXmlObject(strXML)
{
    var xmlDoc = null;

    // code for IE
    if (window.ActiveXObject)
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = false;
        xmlDoc.loadXML(strXML);
        return xmlDoc.documentElement;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument)
    {
        var objParser = new DOMParser();
        xmlDoc = objParser.parseFromString(strXML,"text/xml");
        return xmlDoc.documentElement;
    }
    else
        alert('Your browser does not support loading xml documents');
}

//==============================================================
// returns an attribute from an XML object
//==============================================================
function getXmlAttribute(xmlDoc,strAttributeName)
{
    return xmlDoc.attributes.getNamedItem(strAttributeName).value;
}

//==============================================================
// sets the value of an attribute from an XML object
//==============================================================
function setXmlAttribute(xmlDoc,strAttributeName,strAttributeValue)
{
    return xmlDoc.attributes.getNamedItem(strAttributeName).value = strAttributeValue;
}

//==============================================================
// Checks that the given email address is valid
//==============================================================
function isValidEmail(strEmail)
{   
    var strResult = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return (!strEmail.match(strResult)) ? false : true ;
}

//==============================================================
// Sets a cookie in the browser
//==============================================================
function setCookie(name, value, expires, path, domain, secure ) 
{
    // set time, it's in milliseconds
    var dteToday = new Date();
    dteToday.setTime( dteToday.getTime() );

    /*
    if the expires variable is set, make the correct 
    expires time, the current script below will set 
    it for x number of days, to make it for hours, 
    delete * 24, for minutes, delete * 60 * 24
    */
    if ( expires )
    {
        expires = expires * 1000 * 60 * 60 * 24;
    }

    var expiresDate = new Date( dteToday.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
                            ( ( expires ) ? ";expires=" + expiresDate.toGMTString() : "" ) + 
                            ( ( path ) ? ";path=" + path : "" ) + 
                            ( ( domain ) ? ";domain=" + domain : "" ) +
                            ( ( secure ) ? ";secure" : "" );
}


//==============================================================
// Gets a cookie in the browser
//==============================================================
function getCookie( name ) 
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var arrAllCookies = document.cookie.split( ';' );
	var arrTempCookie = '';
	var strCookieName = '';
	var strCookieValue = '';
	var blnbCookieFound = false; // set boolean t/f default f
	
	for ( i = 0; i < arrAllCookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		arrTempCookie = arrAllCookies[i].split( '=' );
		
		// and trim left/right whitespace while we're at it
		strCookieName = arrTempCookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( strCookieName == name )
		{
			blnbCookieFound = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( arrTempCookie.length > 1 )
			{
				strCookieValue = unescape( arrTempCookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return strCookieValue;
			break;
		}
		arrTempCookie = null;
		strCookieName = '';
	}
	if ( !blnbCookieFound )
	{
		return null;
	}
}		

//==============================================================
// Deletes the cookie when called
//==============================================================
function deleteCookie( name, path, domain ) 
{
    if ( getCookie( name ) )
    { 
            document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
        ( ( domain ) ? ";domain=" + domain : "" ) +
        ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
    }
}

//==============================================================
// Returns constant value for deserialization
//==============================================================
function getXmlTag()
{
    return '<?xml version="1.0" encoding="utf-8" ?>' + '\r\n';
}

//==============================================================
// Replace special characters
//==============================================================
function encodeSpecialCharacters(s)
{
    var strNewString = s;
    
    strNewString = strNewString.replace(new RegExp('&','g'),'&amp;');
    strNewString = strNewString.replace(new RegExp('"','g'),'&quot;');
    strNewString = strNewString.replace(new RegExp('<','g'),'&lt;');
    strNewString = strNewString.replace(new RegExp('>','g'),'&gt;');
    strNewString = strNewString.replace(new RegExp("'",'g'),'&#39;');
    
    return strNewString;
}

//==============================================================
// Replace special characters
//==============================================================
function decodeSpecialCharacters(s)
{
    var strNewString = s;
    
    strNewString = strNewString.replace(new RegExp('&amp;','g'),'&');
    strNewString = strNewString.replace(new RegExp('&quot;','g'),'"');
    strNewString = strNewString.replace(new RegExp('&lt;','g'),'<');
    strNewString = strNewString.replace(new RegExp('&gt;','g'),'>');
    strNewString = strNewString.replace(new RegExp('&#39;','g'),"'");
    
    return strNewString;
}

//==============================================================
// Get absolute coordinates of an element
//==============================================================
function getAbsoluteCoordinates(obj) 
{
    var curLeft     = 0;
    var curTop      = 0;
    var curWidth    = 0;
    var curHeight   = 0;
    
    if (obj.offsetParent) 
    {
        do
        {
            curLeft += obj.offsetLeft;
            curTop += obj.offsetTop;
            curWidth += obj.offsetWidth;
            curHeight += obj.offsetHeight;
        } while (obj = obj.offsetParent);

        return [curLeft,curTop,curWidth,curHeight];
    }
}

function playSound(strSoundFile)
{
    try
    {
        if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
        {
           var objSound = document.getElementById("bgsSound");
           if (!objSound)
           {
                objSound = document.createElement("bgSound");
                if (objSound)
                {
                    objSound.id = "bgsSound";
                    objSound.setAttribute("loop","1");
                    var objBody = document.getElementsByTagName("body").item(0);
                    objBody.appendChild(objSound);
                }
           }
           
           if (objSound)
           {
                objSound.src = strSoundFile;
           }
        }
        else
        {
            var spnSound = document.getElementById("spnSound");
            if (!spnSound)
            {
                objSound = document.createElement("span");
                if (objSound)
                {
                    objSound.id = "spnSound";
                    var objBody = document.getElementsByTagName("body").item(0);
                    objBody.appendChild(objSound);
                }
            }
            
            if (spnSound)
            {
                spnSound.innerHTML = '<embed src="' + strSoundFile + '" hidden="true" autostart="true" loop="false">';
            }
        }
    }
    catch(e)
    {
        //No sound
    }
}