/********************************************************************************
 
Name:     Config
 
*********************************************************************************/
function fnConfig(size) {
    fnFlashDetect();
    fnBrowser();
    //alert(ua);
    }

/********************************************************
Name:             javascript stylesheet
Description:     loads javascript specific stylesheet
********************************************************/




/********************************************************************************
 
Name:     Submit
 
*********************************************************************************/
function fnSubmit(formName) { 
 eval("document.forms['" + formName + "'].submit();");
}  

/* Set up user agent string for browser eval */
var ua = navigator.userAgent.toLowerCase();
/******************************************************************************************
set bolean to detect IE5 Mac
******************************************************************************************/
ieMac = ((ua.indexOf("msie") != -1)&&(ua.indexOf("windows") == -1))? true:false;
    
    
/********************************************************************************
 
Name:     Browser Detect
 
*********************************************************************************/
var iepc,firefox,ns6,ns7,mozilla,safari,OS
function fnBrowser() {    
    var ua = navigator.userAgent.toLowerCase();
    iepc = (((ua.indexOf("msie 7") != -1)||(ua.indexOf("msie 6") != -1)||(ua.indexOf("msie 5.5") != -1))&&(ua.indexOf("windows") != -1)&&(ua.indexOf("opera") == -1))? true:false;
    firefox = ua.indexOf("firefox") != -1 ? true:false; // pc or mac
    nsAll = ua.indexOf("netscape") != -1 ? true:false;
    ns6 = ua.indexOf("netscape6/6") != -1 ? true:false;
    ns7 = ua.indexOf("netscape/7") != -1 ? true:false; // firefox mode
    mozilla = (ua.indexOf("gecko") != -1) && (ua.indexOf("netscape") == -1) ? true:false; 
    safari = ua.indexOf("safari") != -1 ? true:false;
    OS = ua.indexOf("windows") != -1? "PC":"MAC";        
    opera = ua.indexOf("opera/9") != -1 ? true:false;
    if (iepc||firefox||ns7||mozilla||safari||opera) {
        return true;
    } else {
        return false;
    }
}

/********************************************************************************
 
Name:     Popup
 
*********************************************************************************/
function fnPopup(targ,width, height) {
    var obj = targ.href;
    var sScreenX = screen.width;
    var sScreenY = screen.height;
    var x = sScreenX - width;
    var y = sScreenY - height;
    var winLeft = x/2;
    var winTop =  y/2;    
    window.open(obj,"","width=" + width + ",height="+ height + ",scrollbars=no,resizable=yes,left=" + winLeft + ",top=" + winTop);    
    }
    
/********************************************************************************
 
Name:     Popup a window with scrollbars
 
*********************************************************************************/
function fnPopupScroll(targ,width, height) {
    var obj = targ.href;
    var sScreenX = screen.width;
    var sScreenY = screen.height;
    var x = sScreenX - width;
    var y = sScreenY - height;
    var winLeft = x/2;
    var winTop =  y/2;    
    window.open(obj,"","width=" + width + ",height="+ height + ",scrollbars=yes,resizable=yes,left=" + winLeft + ",top=" + winTop);    
    }
    
/********************************************************************************
 
Name:     Flash plugin detect
 
*********************************************************************************/
var flashdetect = false;
var iFlashVersion;
function fnFlashDetect() {
 if (navigator.plugins && navigator.plugins.length) {
  for (x=0; x < navigator.plugins.length; x++) {
   if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
     flashdetect = true;  
     iFlashVersion = eval(navigator.plugins[x].description.split('Shockwave Flash ')[1].split('.')[0]);             
    break;
   }
  }
 }
 else if (window.ActiveXObject) {
  for (x = 2; x <= 20; x++) {
   try {
    oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
    if(oFlash) {
     flashdetect = true;  
        iFlashVersion = x;
       }
   }
   catch(e) {}
  }
 }
}
fnFlashDetect(); // run on file load; 
    
/********************************************************************************
 
Name: Flash embed
Description:  Writeout flash code. Fixes Eolas update for IE as well.
@param swf  String path to swf file
@param width     Number value of movie width
@param height    Number value of movie height
@param alternateContent String of HTML to be served if flash is not installed
 
*********************************************************************************/
 
flash = new Object();
flash.insert = function(swf,width,height,alternateContent) {
    swf = swf.replace(/\./g,"%2E") // encode periods as %2e    
 if(flashdetect) {
 flashObject = '<embed src="'+swf+'" menu="false" quality="high" width="'+width+'px" height="'+height+'px" type="application/x-shockwave-flash" wmode="transparent" salign="T" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
try{ 
    document.getElementById("noFlashContent").style.display = "none";
}
catch(e) {}
 } else {
  flashObject = alternateContent;
 }
 document.write(flashObject);
 
}
 
 
 /********************************************************************************
 
Name:                 Flash embed For The Flash Video Player
Description:          Writeout flash code. Fixes Eolas update for IE as well.
@param swf          String path to swf file
@param width         Number value of movie width
@param height        Number value of movie height
 
*********************************************************************************/
var flashVideo = new Object();
flashVideo.insert = function(swf,width,height,flv) {
    swf = swf.replace(/\./g,"%2E") // encode periods as %2e    
     if(flashdetect && (iFlashVersion >= 8)) {
         flashObject = '<embed src="'+swf+'" FlashVars="flv=' + flv + '" menu="false" quality="high" width="'+width+'px" height="'+height+'px" type="application/x-shockwave-flash" salign="T" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
        document.write(flashObject);
        document.getElementById("noFlashContent").style.display = "none";
    } else {
        document.getElementById("noFlashContent").style.display = "block";
        document.getElementById("flashContent").style.display = "block";
    }
}
 
 
/* New Flash embed methods - TWB added 27.03.08 */ 
/********************************************************************************
Name:                     Flash detect.
Description:            boolean true/false if installed and version number 
                        accessed via flash.version
@var flash.installed    true is flash is installed
@var flash.version        flash player version
*********************************************************************************/
//var flash = new Object();    
flash.installed = false;
if (navigator.plugins && navigator.plugins.length) {
    for (x=0; x < navigator.plugins.length; x++) {
        
        if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {        
            flash.installed = true;                    
            flash.version = eval(navigator.plugins[x].description.split('Shockwave Flash ')[1].split('.')[0]);                    
            break;
        }
    }
}
else if (window.ActiveXObject) {
    for (x = 2; x <= 20; x++) {
        try {
            oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
            if(oFlash) {        
                flash.installed = true;    
                flash.version = x;
            }
        }
        catch(e) {}
    }
}

    
/********************************************************************************
Name:                 Flash embed
Description:        Writeout flash code. Fixes Eolas update for IE as well.
@param    swf            String path to swf file
@param    width        Number value of movie width
@param    height        Number value of movie height
@param    minVersion    minimum required version of flash for swf. defaults to 6
@param     nonFlashId    the id of the container for non-flash content. 
*********************************************************************************/
flash.embed = function(swf,width,height,minVersion,nonFlashId) {        
    swf = swf.replace(/\./g,"%2E") // encode periods as %2e    
    if(!minVersion){minVersion = 6;}    
    if (flash.installed) {
        if(flash.version > minVersion) {        
            flashObject = '<embed src="'+swf+'" menu="false" width="'+width+'" height="'+height+'" scale="noscale" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" salign="T" />';    
            fnHide(nonFlashId);
            document.write(flashObject);    
        }
        else {
            fnShow(nonFlashId);
        }    
    }
}
function fnHide(id) {
    if(!document.getElementById(id)){
        return false
    }
    else {
        var oTarg = document.getElementById(id).style;
        oTarg.position = "absolute";
        oTarg.top = "-5000px";
        oTarg.left = "0";
    }
}
function fnShow(id) {
    if(!document.getElementById(id)){return false};
    var oTarg = document.getElementById(id).style;
    oTarg.position = "static";
    oTarg.top = "";
    oTarg.left = "";
}
 
 
/********************************************************************************
Get "textSize" cookie if it's there and resize
accordingly - if none set assume smallText
@param     textSize        string size of text
*********************************************************************************/
function checkTextSize(){
    var cname="textSize";
    var start = document.cookie.indexOf( cname + "=" );
    var len = start + cname.length + 1;
    
    if ( ( !start ) && ( cname != document.cookie.substring( 0, cname.length ) ) )
    {
        // no cookie set so use small
        sTextSize = "smallText";
    }
    if ( start != -1 ){
        var end = document.cookie.indexOf( ";", len );
        if ( end == -1 ) {
            end = document.cookie.length;
            
            //get cookie value
            sTextSize = unescape( document.cookie.substring( len, end ) );
            fnTSize(sTextSize);
        }
    }
}
/********************************************************************************
Set body class to "small", "medium" or "large" 
Set "textSize" cookie to the size
@param     textSize        string size of text
*********************************************************************************/
function fnTSize(textSize) {    
    // Set body class                                
    document.body.className = textSize;
    // Set cookie
    document.cookie = "textSize="+textSize + "; path=/";    
            
}     
function getParameter ( queryString, parameterName ) {
    // Add "=" to the parameter name (i.e. parameterName=value)
    var parameterName = parameterName + "=";
    if ( queryString.length > 0 ) {
        // Find the beginning of the string
        begin = queryString.indexOf ( parameterName );
        // If the parameter name is not found, skip it, otherwise return the value
        if ( begin != -1 ) {
            // Add the length (integer) to the beginning
            begin += parameterName.length;
            // Multiple parameters are separated by the "&" sign
            end = queryString.indexOf ( "&" , begin );
        if ( end == -1 ) {
            end = queryString.length
        }
        // Return the string
        return unescape ( queryString.substring ( begin, end ) );
    }
        // Return "null" if no parameter has been found
        return "null";
    }
}
function fnInitForm() {
    fnInitFormHelp();
}
function fnInitFormHelp() {        
    if(!nsAll) {
        hideAll();
    }
}

    
    function hideAll(){
      var obj,nextspan,anchor,content
      // get all spans
      obj=document.getElementsByTagName('span')
      // run through them
      for (var i=0;i<obj.length;i++){
        // if it has a class of helpLink
        if(/helpLink/.test(obj[i].className)){
        
          // get the adjacent span
          nextspan=obj[i].nextSibling
          while(nextspan.nodeType!=1) nextspan=nextspan.nextSibling
           // hide it
          nextspan.style.display='none'
          //create a new link
          anchor=document.createElement('a')
          // copy original helpLink text and add attributes
          content=document.createTextNode(obj[i].firstChild.nodeValue)
          anchor.appendChild(content)
          anchor.href='#help'
          anchor.title='Click to show help'
          anchor.className=obj[i].className
          anchor.nextspan=nextspan
          anchor.onclick=function(){showHide(this.nextspan);changeTitle(this);return false}
          // replace span with created link
          obj[i].replaceChild(anchor,obj[i].firstChild);
        }
      }
    }
    
    function changeTitle(obj){    // used to flip helpLink title
      if(obj)
        obj.title = obj.title=='Click to show help' ? 'Click to hide help' : 'Click to show help'
    }
    function showHide(obj){   // used to flip the display property
      if(obj)
        obj.style.display = obj.style.display=='none' ? 'block' : 'none';
    }
    
    
    
    
function fnTextCounter(targ){
    var rows = targ.rows;
    var maxChar;
    charUsed = targ.value.length;
    
    
    if (rows <= 5){
        maxChar = 200;
    }
    else if (rows <= 10){
        maxChar = 500;
    }    
    else if (rows > 11 ) {
        maxChar = 10000000;
    }
    
    charLeft = (maxChar - charUsed);
    
    
    
    
    if ((charUsed >= maxChar)&&(rows < 11)){
        targ.value = targ.value.substring(0, maxChar);
        charLeft = 0;
    } else if(rows < 11) {
        charLeft = (maxChar - charUsed);
    } else {}
    
    
    if(rows < 11) {
        document.getElementById(targ.id.replace("input","counter")).innerHTML = "Characters left: " + charLeft;
    }
    
    
}    
    
    
/**
 * Form builder validation function for text inputs.
 */    
function fnValidateText(oInput, sLabelID, bRequired, sRequiredError, sRegex, sRegexError, sMustMatchID, sMustMatchError)
{
    // Used to record whether the input is valid, and the relavent error message.
    var bValid = true;
    var sError = "";
    // Same logic as in the c# code. Check for required error (trim the value too)
    if (oInput.value.replace(/^\s+|\s+$/g, '').length == 0) {
        bValid = !bRequired;
        sError = sRequiredError;
    }
    else if (sRegex) {
        // test regex
        try {
            var re = new RegExp(sRegex);
            if (!oInput.value.match(re)) {
                bValid = false;
                sError = sRegexError;
            }
        } catch (e) {
            // If it fails then leave it as valid.
        }
    }
    if (bValid && sMustMatchID) {
        // test mustmatch field
        var oMatch = document.getElementById(sMustMatchID);
        if (oMatch) {
            if (oMatch.value != oInput.value) {
                bValid = false;
                sError = sMustMatchError;
            }
        }
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Form builder validation function for text areas.
 */    
function fnValidateTextArea(oInput, sLabelID, bRequired, sRequiredError)
{
    // Used to record whether the input is valid, and the relavent error message.
    var bValid = true;
    var sError = "";
    // Check for required error (trim the value too)
    if (bRequired && oInput.value.replace(/^\s+|\s+$/g, '').length == 0) {
        bValid = false;
        sError = sRequiredError;
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Form builder validation function for drop downs.
 */    
function fnValidateSelect(oInput, sLabelID, bRequired, sRequiredError)
{
    // Used to record whether the input is valid, and the relavent error message.
    var bValid = true;
    var sError = "";
    
    // Check for required error (values are always padded with 4 chars)
    if (bRequired && oInput.options[oInput.selectedIndex].value.length == 4) {
        bValid = false;
        sError = sRequiredError;
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Form builder validation function for drop downs.
 */    
function fnValidateFile(oInput, sLabelID, bRequired, sRequiredError, sFileTypes, sFileTypesError)
{
    // Used to record whether the input is valid, and the relavent error message.
    var bValid = true;
    var sError = "";
    
    // Check for required error
    if (bRequired && oInput.value.length == 0) {
        bValid = false;
        sError = sRequiredError;
    }
    else if (oInput.value.length > 0 && sFileTypes.length > 0) {
        bValid = false;
        
        var sFileType = oInput.value.substring(oInput.value.lastIndexOf(".") + 1);
        
        // check for invalid file type
        var fileTypes = sFileTypes.split(",");
        for(i = 0; i < fileTypes.length; i++){
            // trim and lower case
            fileTypes[i] = fileTypes[i].replace(/^\s+|\s+$/g, '').toLowerCase();
            
            // remove any dot
            if (fileTypes[i].charAt(0) == ".") fileTypes[i] = fileTypes[i].substring(1);
            
            // compare
            if (fileTypes[i] == sFileType.toLowerCase()) {
                bValid = true;
                break;
            }
        }
        
        if (!bValid) {
            if (sFileTypesError.length > 0) {
                sError = sFileTypesError;
            }
            else {
                sError = "The file must be one of: " + sFileTypes;
            }
        }
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Form builder validation function for checkbox.
 */    
function fnValidateCheckbox(oInput, sLabelID, bRequired, sRequiredError)
{
    // Used to record whether the input is valid, and the relavent error message.
    var bValid = true;
    var sError = "";
    
    // Check for required error (values are always padded with 4 chars)
    if (bRequired && !oInput.checked) {
        bValid = false;
        sError = sRequiredError;
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Form builder validation function for checkbox list.
 */    
function fnValidateCheckboxList(oInput, sLabelID, bRequired, sRequiredError)
{
    // Used to record whether the input is valid, and the relavent error message.
    var bValid = true;
    var sError = sRequiredError;
    
    // Check for required error (values are always padded with 4 chars)
    if (bRequired) 
    {
        // Loop through all checkboxes and see if one is checked.
        var oAllInputs = oInput.parentNode.getElementsByTagName("input");
        bValid = false;
        
        // If you find a checked one then set it to valid and end.
        for (var i = 0; i < oAllInputs.length; i++) {
            if (oAllInputs[i].checked) {
                bValid = true;
                break;
            }
        }
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Form builder validation function for radio buttons.
 */    
function fnValidateRadioList(oInput, sLabelID, bRequired, sRequiredError, bAllowSubmit)
{
    // Used to record whether the input is valid, and the relavent error message.
    var bValid = true;
    var sError = sRequiredError;
    
    // Check for required error (values are always padded with 4 chars)
    if (bRequired) 
    {
        // Loop through all checkboxes and see if one is checked.
        var oAllInputs = oInput.parentNode.getElementsByTagName("input");
        bValid = false;
        
        // If you find a checked one then set it to valid and end.
        for (var i = 0; i < oAllInputs.length; i++) {
            if (oAllInputs[i].checked) {
                bValid = true;
                break;
            }
        }
    }
    
    // If its valid so far, check whether this radio button is good
    if (bValid) {
        if (oInput.checked) {
            bValid = bAllowSubmit;
        }
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Form builder validation function for date picker.
 * sInputPrefix - The prefix of IDs used by date picker selects, e.g. input42_day = input42
 */
function fnValidateDatePicker(sInputPrefix, sLabelID, bRequired, sRequiredError, lFrom, sFromError, lTo, sToError) {
    var bValid = true;
    var sError = "";
    
    // Get a handle on the 3 dropdowns.
    var oDay = document.getElementById(sInputPrefix + "_day");
    var oMonth = document.getElementById(sInputPrefix + "_month");
    var oYear = document.getElementById(sInputPrefix + "_year");
    
    // If required and date not chosen, error.
    if (bRequired && (oYear.options[oYear.selectedIndex].value.length == 0 || oMonth.options[oMonth.selectedIndex].value.length == 0 || oDay.options[oDay.selectedIndex].value.length == 0)) {
        bValid = false;
        sError = sRequiredError;
    }
    else
    {
        // A date is chosen. No easy way to valididate dates in JS as it just goes over to the next month e.g. on feb.
        var oDate = new Date();
        oDate.setFullYear(oYear.options[oYear.selectedIndex].value, oMonth.options[oMonth.selectedIndex].value - 1, oDay.options[oDay.selectedIndex].value);
        oDate.setHours(0);
        oDate.setMinutes(0);
        oDate.setSeconds(0);
        oDate.setMilliseconds(0);
        lDate = oDate.getTime();
        
        if (isNaN(lDate)) {
            // If invalid date chosen, error.
            bValid = false;
            sError = sRequiredError;
        }
        else 
        {
            // A valid date is chosen, or at least one that JS can parse.
            // If not within date range, error.
            if (lDate < lFrom) {
                var oFrom = new Date();
                oFrom.setTime(lFrom);
                bValid = false;
                sError = sFromError + oFrom.getDate() + "/" + (oFrom.getMonth() + 1) + "/" + oFrom.getFullYear();
            }
            else if (lDate > lTo) {
                var oTo = new Date();
                oTo.setTime(lTo);
                bValid = false;
                sError = sToError + oTo.getDate() + "/" + (oTo.getMonth() + 1) + "/" + oTo.getFullYear();
            }
        }
    }
    
    fnDisplayTickCross(sLabelID, bValid, sError);
}
/**
 * Display the tick or cross and error message in the <em> of the label (id) passed in.
 */
function fnDisplayTickCross (sLabelID, bValid, sError) {
    // Target <label>    
    var oLabel = document.getElementById(sLabelID);
    if (!oLabel) return;
    
    // Build <em> tags in labels if they are missing 
    if (!oLabel.getElementsByTagName("em")[0]) {
        var myEm = document.createElement("em");        
        oLabel.appendChild(myEm);
    }    
    
    // Get output target (EM)
    var outputTarget = oLabel.getElementsByTagName("em")[0];
    // Set the validation message on the field.
    if (bValid) {
        outputTarget.className = "tick";
        outputTarget.innerHTML = "&nbsp;";
    } else {
        if (typeof(sError) == "undefined" || sError.length == 0) {
            sError = "&nbsp;";
        }
        outputTarget.className = "cross";
        outputTarget.innerHTML = sError;
    }
}

/**
 * Writes the HTML for the calendar button. It's in JS because the calendar only works with JS.
 */
function fnWriteCalendarButton (sInputPrefix) {
    document.write('<div class="calendarWrap">');
    document.write('<a href="#" class="dateChooserLink" title="Open calendar" ');
    document.write(' onclick="return fnOpenDatePicker(\'' + sInputPrefix + '\',this)">Open calendar</a>');
    document.write('</div>');
}

/**
 * Fires when you click the calendar link.
 * Opens the calendar in the right place. Only one calendar exists on the page, it is reused.
 */
function fnOpenDatePicker(sInputPrefix, oLink)
{    
    // Create date picker instance if it doesn't already exist
    if (!document.DateChooser)
    {
        document.DateChooser = new DateChooser();
        // Check if the browser has fully loaded the DateChooser object, and supports it.
        if (!document.DateChooser.display)
        {
            return false;
        }
        // Set generic properties.
        document.DateChooser.setCloseTime(1000);
        document.DateChooser.setXOffset(10);
        document.DateChooser.setYOffset(-10);
    }
    
    // Check if the browser has fully loaded the DateChooser object, and supports it.
    if (!document.DateChooser.display)
    {
        return false;
    }
    // Tell it to update these fields.                
    eval ("var t = {'" + sInputPrefix + "_day':'j', '" + sInputPrefix + "_month':'n', '" + sInputPrefix + "_year':'Y'};");
    document.DateChooser.setUpdateField(t);
    
    // Get a handle on the 3 dropdowns.
    var oDay = document.getElementById(sInputPrefix + "_day");
    var oMonth = document.getElementById(sInputPrefix + "_month");
    var oYear = document.getElementById(sInputPrefix + "_year");
    
    // Set the earliest and latest date to show on the calendar
    var d = new Date();    
    if (oDay[0].value.length == 0 && oMonth[0].value.length == 0 && oYear[0].value.length == 0) {
        // If "day" "month" "year" options are shown
        d.setFullYear(oYear.options[1].value, oMonth.options[1].value - 1, oDay.options[1].value);
        document.DateChooser.setEarliestDate(d);
    }
    else {
        // No day month year options. 
        d.setFullYear(oYear.options[0].value, oMonth.options[0].value - 1, oDay.options[0].value);
        document.DateChooser.setEarliestDate(d);
    }
    d.setFullYear(oYear.options[oYear.options.length - 1].value, oMonth.options[oMonth.options.length - 1].value - 1, oDay.options[oDay.options.length - 1].value);
    document.DateChooser.setLatestDate(d);        
    
    // If a date is already chosen then set it into the calendar.
    if (oYear.options[oYear.selectedIndex].value.length != 0 && oMonth.options[oMonth.selectedIndex].value.length != 0 && oDay.options[oDay.selectedIndex].value.length != 0)
    {
        d.setFullYear(oYear.options[oYear.selectedIndex].value, oMonth.options[oMonth.selectedIndex].value - 1, oDay.options[oDay.selectedIndex].value);
        document.DateChooser.setSelectedDate(d);
    }
    
    // The update function just invokes validation on the date field.
    document.DateChooser.setUpdateFunction(fnDateChosen);
    
    // Create dummy eventargs object to tell the date picker the link target for positioning calendar.
    var e = new Object();
    e.target = oLink;
    document.DateChooser.display(e);
    
    // Don't follow the link
    return false;
}
/**
 * Fires after a date has been chosen. 
 * We use it to run the validation on this field.
 */
function fnDateChosen (date, fields) {
    for(stuff in fields) {
        var ddl = document.getElementById(stuff);
        if (ddl != null) {
            if (ddl.onblur) {
                ddl.onblur();
            }
        }
    }
}
