﻿Cufon.replace('.cufon-gradient', { color: '-linear-gradient(#ff7b35, #ff2300)' });
Cufon.replace('.cufon');
Cufon.replace('.cufon-gradient a, a.cufon-gradient, .cufon a, a.cufon', { hover: true });

if (document.documentElement && document.getElementById) {
    var docClass = document.documentElement.className != null ? document.documentElement.className : document.documentElement.getAttribute('class');
    docClass = docClass != '' ? docClass + ' jsEnabled' : 'jsEnabled';
    document.documentElement.setAttribute('class', docClass);
    document.documentElement.className = docClass; //For IE
}

var akHistory = {
    akCookie: new Hash.Cookie('akHistoryCookie', { duration: 365, path: "/"}),
    update: function() {
        var landedPage = cleanUrl(location.href);
        var cookieCurrentPage = akHistory.akCookie.get('c');
        var cookiePreviousPage = akHistory.akCookie.get('p');

        if (landedPage.indexOf('/activekids/logon/logon.aspx') == -1 && landedPage !== cookieCurrentPage) {
            akHistory.akCookie.set('p', cookieCurrentPage);
            akHistory.akCookie.set('c', landedPage);
        };

        function cleanUrl(url) {
            var urlSplitted = url.toLowerCase().split("/");
            for (var i = 0, max = urlSplitted.length; i < max; i++) {
                if (urlSplitted[0] !== "activekids") {
                    urlSplitted.shift();
                };
            };
            return unescape("/" + urlSplitted.join("/").split("default.aspx").join(""));
        };
    },
    getPrevious: function() {
        return akHistory.akCookie.get('p');
    }
};

akHistory.update();

// Back function - it adds the history back behaviour
var akBackLink = {
    init: function(sTargetEl, useCookie) {
        var btnCode = "<div><div><a href=\"#\"><span>Back</span></a></div></div>";
        var btnContainer = $$(sTargetEl);
        if (btnContainer) {
            btnContainer.addClass('button');
            btnContainer.setHTML(btnCode);
            btnLink = btnContainer.getElement('a');
            btnLink.addEvent('click', function(event) {
                var event = new Event(event);
                event.stop();
                if (useCookie == true && akHistory.getPrevious() !== null) {
                    location.replace(akHistory.getPrevious());
                } else {
                    history.go(-1);
                }
            });
            return btnLink;
        };
    }
};

// Print function - it replace an empty container with a print button
var akPrintLink = {
    init: function(sTargetEl) {
        if (!window.print) { return; }
        var btnCode = "<div><div><a href=\"#\"><span>Print</span></a></div></div>";
        var btnContainer = $$(sTargetEl);
        if (btnContainer) {
            btnContainer.addClass('button').addClass('print');
            btnContainer.setHTML(btnCode);
            btnLink = btnContainer.getElement('a');
            btnLink.addEvent('click', function(event) {
                var event = new Event(event);
                event.stop();
                window.print();
            });
            return btnLink;
        };
    }
};

// Preview Letter - it create the overlay effect for letters in the CommunicationsTooklit area
var akPreviewLetter = {
    init: function() {
        var akContent = $('akContent'),
					akContentSize = null,
					akLetterPreview = $('akLetterPreview'),
					akLettersOverlay = new Element('div', {
					    'id': 'akLettersOverlay',
					    'styles': {
					        'position': 'absolute',
					        'top': '0px',
					        'left': '0px',
					        'width': '975px',
					        'background-color': '#000',
					        'z-index': '9'
					    }
					});

        if (akLetterPreview) {
            akLetterPreview.setStyles({
                'position': 'absolute',
                'z-index': '10',
                'top': '0',
                'left': '105px',
                'width': '770px'
            });
            akLetterPreview.injectInside(akContent);
            akNavigationControl.updateOverlay();
            akContentSize = akContent.getCoordinates(),
					akLettersOverlay.setStyle('height', akContentSize.height);
            akLettersOverlay.injectBefore(akLetterPreview).setOpacity(0.7);
        };
    }
};


// Videoplayer - gets the video number as a parameter and plays it into #videoplayer
var akVideoplayerControl = {
    videoFiles: [
                "http://c0531312.cdn.cloudfiles.rackspacecloud.com/montage.flv",
                "http://c0531312.cdn.cloudfiles.rackspacecloud.com/cults.flv",
                "http://c0531312.cdn.cloudfiles.rackspacecloud.com/downshire.flv",
                "http://c0531312.cdn.cloudfiles.rackspacecloud.com/drumchapel.flv",
                "http://c0531312.cdn.cloudfiles.rackspacecloud.com/ingfield.flv",
                "http://c0531312.cdn.cloudfiles.rackspacecloud.com/lanishen.flv",
                "http://c0531312.cdn.cloudfiles.rackspacecloud.com/pgl.flv"
                ],
    imagePathData: [
                "/activekids/library/images/videoplayer/montage.jpg",
                "/activekids/library/images/videoplayer/cults.jpg",
                "/activekids/library/images/videoplayer/downshire.jpg",
                "/activekids/library/images/videoplayer/drumchapel.jpg",
                "/activekids/library/images/videoplayer/ingfield.jpg",
                "/activekids/library/images/videoplayer/lanishen.jpg",
                "/activekids/library/images/videoplayer/pgl.jpg"
                ],
    startTrackData: [
                "('DCS.dcsuri','/activekids/home/video/start.flashPage','WT.ti','AK10 Homepage - Video - Start','WT.cg_n','Active Kids','WT.cg_s','Homepage','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/start.flashPage','WT.ti','AK10 Info Zone - Video - Start - Cults Primary School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/start.flashPage','WT.ti','AK10 Info Zone - Video - Start - Downshire Primary School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/start.flashPage','WT.ti','AK10 Info Zone - Video - Start - Drumpchapel Scouts','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/start.flashPage','WT.ti','AK10 Info Zone - Video - Start - Ingfield Manor Special School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/start.flashPage','WT.ti','AK10 Info Zone - Video - Start - Llanishen High School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/start.flashPage','WT.ti','AK10 Info Zone - Video - Start - St Thomas More Catholic Comprehensive','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                ],
    stopTrackData: [
                "('DCS.dcsuri','/activekids/home/video/complete.flashPage','WT.ti','AK10 Homepage - Video - End','WT.cg_n','Active Kids','WT.cg_s','Homepage','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/end.flashPage','WT.ti','AK10 Info Zone - Video - End - Cults Primary School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/end.flashPage','WT.ti','AK10 Info Zone - Video - End - Downshire Primary School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/end.flashPage','WT.ti','AK10 Info Zone - Video - End - Drumpchapel Scouts','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/end.flashPage','WT.ti','AK10 Info Zone - Video - End - Ingfield Manor Special School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/end.flashPage','WT.ti','AK10 Info Zone - Video - End - Llanishen High School','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                "('DCS.dcsuri','/activekids/info/home/video/end.flashPage','WT.ti','AK10 Info Zone - Video - End - St Thomas More Catholic Comprehensive','WT.cg_n','Active Kids','WT.cg_s','Info zone','WT.cg_t','Video')",
                ],
    returnVars: function(videoNum) {
        var flashvars = {
            configPath: "/activekids/library/flash/applicationContext.xml",
            imagePath: akVideoplayerControl.imagePathData[videoNum],
            flvPath: akVideoplayerControl.videoFiles[videoNum],
            startTrack: akVideoplayerControl.startTrackData[videoNum],
            stopTrack: akVideoplayerControl.stopTrackData[videoNum]
        };
        return flashvars;
    },
    returnParams: function() {
        var params = {
            bgcolor: '#ffffff',
            menu: "false",
            wmode: "opaque",
            scale: "default",
            allowFullScreen: "true",
            allowScriptAccess: "always"
        };
        return params;
    },
    returnAttr: function() {
        var attributes = {};
        return attributes;
    },
    embed: function(videoNum) {
        //swfobject.switchOffAutoHideShow();
        swfobject.embedSWF("/activekids/library/flash/videoplayer.swf", "videoplayer", "498", "320", "9.0.0", "/activekids/library/flash/expressInstall.swf", akVideoplayerControl.returnVars(videoNum), akVideoplayerControl.returnParams(), akVideoplayerControl.returnAttr());
    },   
    replace: function (videoNum) {
        
		var videoplayer = $('videoplayer'),
			container = $('videoContainer');
		
        if ($chk(videoplayer)) {
			swfobject.removeSWF("videoplayer");
		}
		
		videoplayer = new Element('div', { 'id': 'videoplayer' });
		videoplayer.injectInside(container);
        akVideoplayerControl.embed(videoNum);
    }
}

// moved to a function so that this can be called in info box windows

// This JavaScript will be run when the page has completed loading
window.addEvent('domready', function() {

    //Show any element with noScriptHide class
    $$('.noScript').each(function(el) { el.setStyle('display', 'none'); });
    $$('.noScriptHide').each(function(el) { el.removeClass('noScriptHide'); });
    $$('.btnPrintPage').each(function(el) { el.setStyle('display', 'block'); el.addEvent('click', function(e) { e = new Event(e).stop(); window.print(); }); });

    if ($('lnkLogin')) {

        if ($$('.loginNavigation')[0].hasClass('open')) {
            $$('.whichCatalogue').setStyle('display', 'none');
        } else {
            $$('.whichCatalogue').setStyle('display', 'block');
        }

        $('lnkLogin').addEvent('click', function(e) {
            e = new Event(e).stop();

            if ($$('.loginNavigation')[0].hasClass('open')) {
                $$('.loginNavigation')[0].removeClass('open');
                $$('.whichCatalogue').setStyle('display', 'block');

            } else {
                $$('.loginNavigation')[0].addClass('open');
                $$('.whichCatalogue').setStyle('display', 'none');
            }

            return false;
        });
    }
    if ($('ctl00_searchBarValue')) {
        var linkButton = $("ctl00_CatalogueSearch").getLast().getLast().getLast().getLast();
        $(linkButton).setProperty('href', 'javascript:void(0)');
        $('ctl00_searchBarValue').addEvent('focus', function(e) {
            if ($('ctl00_searchBarValue').getProperty('value') == 'e.g. footballs') {
                $('ctl00_searchBarValue').setProperty('value', '');
                $(linkButton).setProperty('href', "javascript:__doPostBack('ctl00$lnkSearch','')");
            }
        });
        $('ctl00_searchBarValue').addEvent('blur', function(e) {
            if ($('ctl00_searchBarValue').getProperty('value') == '') {
                $('ctl00_searchBarValue').setProperty('value', 'e.g. footballs');
                $(linkButton).setProperty('href', 'javascript:void(0)');
            }
        });
    }
});


// Search box
function swSearch() {
	if (document.getElementById('queryBox').value == ""){
		alert("Please enter some search criteria");
		document.getElementById('queryBox').focus();
   		return false;
	} else {
		return true
	}
}

function fnTrapKD(btnID, event){
btn = findObj(btnID);
 if (document.all){
  if (event.keyCode == 13){
   event.returnValue=false;
   event.cancel = true;
   btn.click();
  }
 }
 else if (document.getElementById){
  if (event.which == 13){
   event.returnValue=false;
   event.cancel = true;
   btn.focus();
   btn.click();
  }
 }
 else if(document.layers){
  if(event.which == 13){
   event.returnValue=false;
   event.cancel = true;
   btn.focus();
   btn.click();
  }
 }
}

function findObj(n, d) { 
	var p,i,x;  
	if(!d) 
		d=document; 
	if((p=n.indexOf("?"))>0 && parent.frames.length) {
		d=parent.frames[n.substring(p+1)].document; 
		n=n.substring(0,p);
	}
	if(!(x=d[n])&&d.all) 
		x=d.all[n]; 
	for (i=0;!x&&i<d.forms.length;i++) 
		x=d.forms[i][n];
	for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
		x=findObj(n,d.layers[i].document);
	if(!x && d.getElementById) 
		x=d.getElementById(n); 
	return x;
}

// akNavigation
var akNavigationControl = {
    initiated: false,
    speed: 150,
    opened: false,
    clickActivated: false,
    intentID: null,
    intentTimeout: 300,
    akContent: null,
    akContentOverlay: null,

    updateOverlay: function() {
        var akContentSize = akNavigationControl.akContent.getCoordinates();
        akNavigationControl.akContentOverlay.setStyle('height', akContentSize.height)
    },

    init: function() {
        if (!akNavigationControl.initiated) {

            akNavigationControl.initiated = true;
            akNavigationControl.akContent = $('akContent');
            akNavigationControl.akContentOverlay = new Element('div', {
                'id': 'akContentOverlay',
                'styles': {
                    'position': 'absolute',
                    'top': '0px',
                    'left': '0px',
                    'width': '975px',
                    'background-color': '#000',
                    'z-index': '49'
                }
            });
            
            akNavigationControl.updateOverlay();

            var navArea = $('akNavigation');
            var navButtonDiv = $('akNavigationButton');
            var navButton = new Element('a', { href: '#' }).setText(navButtonDiv.getText());
            var navContent = $('akNavigationContent');
            var fadeNav = navContent.effect('opacity', { duration: akNavigationControl.speed, wait: false });
            var fadeOverlay = akNavigationControl.akContentOverlay.effect('opacity', { duration: akNavigationControl.speed, wait: false });

            function initContent() {
                akNavigationControl.initiated = true;
                navButtonDiv.empty().adopt(navButton);
                akNavigationControl.akContentOverlay.injectInside(akNavigationControl.akContent);
                fadeNav.hide();
                fadeOverlay.hide();
                navButton.addEvent('focus', onFocus);
                navButton.addEvent('click', onClick);
                navButton.addEvent('blur', onBlur);
                navArea.addEvent('mouseleave', onLeave);
                navArea.addEvent('mouseenter', onEnter);
            };

            function onClick(event) {
                event = new Event(event);
                if (akNavigationControl.clickActivated) {
                    toggleMenu(event, null);
                } else {
                    akNavigationControl.clickActivated = true;
                }
                event.preventDefault();
            };

            function onFocus(event) {
                event = new Event(event);
                toggleMenu(event, true);
            };

            function onBlur(event) {
                event = new Event(event);
                //toggleMenu(event);
            };

            function onLeave(event) {
                event = new Event(event);
                checkIntent(event);
                //toggleMenu(event, false);
            };

            function onEnter(event) {
                event = new Event(event);
                if (akNavigationControl.intentID != null) {
                    clearTimeout(akNavigationControl.intentID);
                    akNavigationControl.intentID = null;
                };
            };

            function checkIntent(event) {
                akNavigationControl.intentID = setTimeout(function() { toggleMenu(event, false) }, akNavigationControl.intentTimeout);
            };

            function toggleMenu(event, force) {
                if (event.type === 'focus') {
                    akNavigationControl.clickActivated = false;
                } else {
                    akNavigationControl.clickActivated = true;
                }
                if (force != null) {
                    akNavigationControl.opened = force;
                } else {
                    akNavigationControl.opened = (akNavigationControl.opened == false) ? true : false;
                }
                if (akNavigationControl.opened === true) {
                    fadeOverlay.start(0, 0.7);
                    fadeNav.start(0, 1);
                    // this function is the one used for the website main navigation...
                    hideSelects();
                } else {
                    fadeNav.start(0);
                    fadeOverlay.start(0);
                    // this function is the one used for the website main navigation...
                    showSelects();
                };
            };

            initContent();
        }
    }
}

window.addEvent('domready', function() {
    akNavigationControl.init();
});

// tooltip
window.addEvent('domready', function() {
	// show tooltips on load
	$$('.toolTipLink').each( function(el) { el.setStyle('display', 'inline'); } );
	$$('.toolTipLinkLeft').each( function(el) { el.setStyle('display', 'inline'); } );
	
	// tool tip help - right arrow
	if ($chk($$('.toolTipLink'))) {
		$$('.toolTipLink').each( function(el) {
			el.addEvent('click', function(ev) {
				ev = new Event(ev).stop();
				showToolTip(el,true);
			})
		});
	}
	// tool tip help - left arrow 
	if ($chk($$('.toolTipLinkLeft'))) {
		$$('.toolTipLinkLeft').each( function(el) {
			el.addEvent('click', function(ev) {
				ev = new Event(ev).stop();
				showToolTip(el,false);
			})
		});
	}
});

/* Standard bubble tool tips (object,boolean) */
function showToolTip(el,appearOnRight) {
	
	var toolTipWidth = 274;
	var arrowOffsetX = 3;
	var arrowOffsetY = 34;
	var toolTipMultiples = false;
	var toolTipId = 'toolTipHelpBubble';
	var errorMsg = '<h6 class="error" style="display:block">An error has occurred</h6>' + 
		'<p class="info">Either the \'rel\' attribute or the linking container of the tooltip icon is not correctly defined!</p>';
	
	if (el) {
		
		// set position of where the tooltip should spawn from
		position = el.getPosition();
		
		// get position of content container - set to relative for breadcrumb and image display
		containerPosition = $('content').getPosition();
		
		// adjust position to take into account the container
		position.x =(position.x - containerPosition.x);
		position.y =(position.y - containerPosition.y);
		
		// get middle coordinate of icon, and then adjust tooltip y position relative to where the image arrow appears
		position.x += (el.offsetWidth/2);
		position.y += (el.offsetHeight/2) - arrowOffsetY;
		
		// get the properties of the window
		page = Window.getSize();
				
		/* if the tooltip is meant to sit on the right, but could go off
		 the right side of the screen, place it to the left */
		if (appearOnRight && (position.x + toolTipWidth) > (page.size.x)) appearOnRight = false;		
			
		/* check the left side has enough space for the tooltip, if not place it on the 
		 right. if both sides are not wide enough, it'll go to the right as this is default behaviour */
		if (!appearOnRight && (position.x - toolTipWidth) < 0) appearOnRight = true;
		
		// if it's the left, adjust the position
		if (!appearOnRight) position.x += -toolTipWidth;
		
		// adjust tooltip x position relative to where the image arrow appears
		position.x += (appearOnRight) ? -arrowOffsetX : arrowOffsetX;
		
		// set the CSS base class relative to the arrow direction
		var cssDirection = (!appearOnRight) ? "toolTipRight" : "toolTipLeft";
		
		// remove any existing toolTips if multiples are not allowed
		if ((!toolTipMultiples) && $(toolTipId)) Element.remove($('toolTipHelpBubble'));
		
		// add a unique tooltipe Id if multiples are allowed
		if (toolTipMultiples) toolTipId += position.x + '-' + position.y;
	
		var toolTipBase = new Element('div', { 'id': toolTipId, 'class': 'toolTip ' + cssDirection });
		toolTipBase.setStyle('top', (position.y)+'px');
		toolTipBase.setStyle('left', (position.x)+'px');

		// create markup for tool tip
		var toolTipArrow = new Element('div', {	'class': 'toolTipArrow' });
		$(toolTipArrow).injectInside(toolTipBase);
		
		var toolTipBody = new Element('div', {	'class': 'toolTipBody' });
		$(toolTipBody).injectInside(toolTipArrow);
		
		var toolTipFooter = new Element('div', {	'class': 'toolTipFooter' });
		$(toolTipFooter).injectInside(toolTipBase);
		
		// create close button for help text
		var toolTipClose = new Element('a', {	'class': 'toolTipClose' });
		toolTipClose.innerHTML = 'Close';
		toolTipClose.addEvent('click', function(e) {
			e = new Event(e).stop();
			Element.remove($(toolTipBase));
			
			$$('select').each(function(obj){
				obj.setStyle('visibility', 'visible');
			});
			
		});
		
		$(toolTipClose).injectInside(toolTipBody);
		
		// set a warning message should no help text been defined.
		var helpText = errorMsg;
		
		if ($(el).rel) {
			var helpText = $(el.rel).innerHTML;
		
			if (el.title != '') {
				var toolTipHeader = new Element('h6');
				$(toolTipHeader).innerHTML = el.title;
				$(toolTipHeader).injectInside(toolTipBody);
			}
		}
		toolTipHelpText = helpText;
		
		var toolTipText = new Element('div');
		$(toolTipText).innerHTML = toolTipHelpText;
		$(toolTipText).injectInside(toolTipBody);
		
		$(toolTipBase).injectAfter(el);
	
		// internet explorer 6 will place select boxes above the dropdown, hide them
		if (window.ie6){
			$$('select').each(function(obj){
				
				// get the coordinates of the tooltips and dropdowns
				toolTipCoords = $(toolTipBase).getCoordinates();
				dropDownCoords = obj.getCoordinates();
				
				// if a drop down is underneath the tooltip, then hide it.
				if (((dropDownCoords.left > toolTipCoords.left) && (dropDownCoords.left < toolTipCoords.right) &&
						(dropDownCoords.top > toolTipCoords.top) && (dropDownCoords.top < toolTipCoords.bottom)) ||
						((dropDownCoords.left > toolTipCoords.left) && (dropDownCoords.left < toolTipCoords.right) &&
						(dropDownCoords.bottom > toolTipCoords.top) && (dropDownCoords.bottom < toolTipCoords.bottom)) ||
						((dropDownCoords.right > toolTipCoords.left) && (dropDownCoords.right < toolTipCoords.right) &&
						(dropDownCoords.top > toolTipCoords.top) && (dropDownCoords.top < toolTipCoords.bottom)) ||
						((dropDownCoords.right > toolTipCoords.left) && (dropDownCoords.right < toolTipCoords.right) &&
						(dropDownCoords.bottom > toolTipCoords.top) && (dropDownCoords.bottom < toolTipCoords.bottom))) {
					obj.setStyle('visibility', 'hidden');
				}
			});
		}
	}
	return false;
}

function setAccessibleCookie(accessible) {
    var today = new Date();
    today.setTime(today.getTime() + 15 * 60 * 1000); // + 15 mins
    document.cookie = 'accessible=' + accessible + ';expires=' + today.toGMTString() + ';path=/';
}

//Code Validation

function ValidateCheckCharacter(source, arguments) {

    var baseId;

    if (source.substring(source.length - 3) == "One" || source.substring(source.length - 3) == "Two")
    { baseId = source.substring(0, source.length - 3); }
    if (source.substring(source.length - 5) == "Three")
    { baseId = source.substring(0, source.length - 5); }

    var codePartOne = $(baseId + "One");
    var codePartTwo = $(baseId + "Two");
    var codePartThree = $(baseId  + "Three");
    
    if(codePartOne.value != "" && codePartTwo.value != "" && codePartThree.value != "") {
        
        var code = codePartOne.value + codePartTwo.value + codePartThree.value;
        var result = CheckCharacter(code.toUpperCase());
    
        var container = $(source).getParent();
        
        var errorNode = container.getElementsByTagName('p')[0];
        errorNode.innerHTML = (result) ? "" : "Invalid entry code, please try again.";
        
        return result; 
    }
    else {
        return true;
    }
       
}

function CheckCharacter(input) {

    var factor = 1;
    var sum = 0;
    var n = 16;

    for (i = input.length - 1; i >= 0; i--) {
        var codePoint = GetCodePointFromCharacter(input.charAt(i));
        var addend = factor * codePoint;

        factor = (factor == 2) ? 1 : 2;

        addend = Math.floor(addend / n) + (addend % n);
        sum += addend;
    }

    var remainder = sum % n;
    return (remainder == 0);
}

function GetCodePointFromCharacter(c) {
    var codes = "ZT62R7NPHMBFDJ9G";
    return codes.indexOf(c);
}

/*------------------------------------------*/
/* customised control validators */
/*------------------------------------------*/
function IsValid(controltovalidate) {
    for (i = 0; i < Page_Validators.length; i++) {
        if (Page_Validators[i].controltovalidate == controltovalidate) {
            if (!Page_Validators[i].isvalid) {
                return false;
            }
        }
    }
    return true;
}

function StyleChangingRequiredFieldValidator_Verify(control) {

    var controlToValidate = document.getElementById(control.controltovalidate);

    if (controlToValidate != null) {
        if (controlToValidate.tagName == "INPUT" || controlToValidate.tagName == "SELECT" || controlToValidate.tagName == "TEXTAREA") {
            var controlToChange = document.getElementById(control.controltochange);

            if (control.enabled == "False") {
                // If not already invalid; toggle css class
                if (IsValid(control.controltovalidate)) {
                    controlToChange.attributes['class'].value = control.originalcssclass;
                }
                return true;
            }

            if (controlToValidate.value.length == 0) {
                controlToChange.attributes['class'].value = control.changecssclass;
                return false;
            }
            else {
                // If not already invalid; toggle css class
                if (IsValid(control.controltovalidate)) {
                    controlToChange.attributes['class'].value = control.originalcssclass;
                }
                return true;
            }
        }
    }
    return true;
}
function StyleChangingRegularExpressionValidator_Verify(control) {
    var controlToValidate = document.getElementById(control.controltovalidate);

    if (controlToValidate != null) {
        if (controlToValidate.tagName == "INPUT" || controlToValidate.tagName == "TEXTAREA") {
            var controlToChange = document.getElementById(control.controltochange);
            if (controlToValidate.value.length > 0) {
                var validationExpression = new RegExp(control.validationexpression);
                if (!controlToValidate.value.match(validationExpression)) {
                    controlToChange.attributes['class'].value = control.changecssclass;
                    return false;
                }
                else {
                    // If not already invalid; toggle css class
                    if (IsValid(control.controltovalidate)) {
                        controlToChange.attributes['class'].value = control.originalcssclass;
                    }
                    return true;
                }
            }
        }
    }
    return true;
}
function StyleChangingCompareValidator_Verify(control) {
    var controlToValidate = document.getElementById(control.controltovalidate);
    if (controlToValidate != null) {
        if (controlToValidate.value.length > 0) {
            var controlToChange = document.getElementById(control.controltochange);
            var controlToCompare = document.getElementById(control.controltocompare);
            if (controlToValidate.value != controlToCompare.value) {
                controlToChange.attributes['class'].value = control.changecssclass;
                return false;
            }
            else {
                // If not already invalid; toggle css class
                if (IsValid(control.controltovalidate)) {
                    controlToChange.attributes['class'].value = control.originalcssclass;
                }
                return true;
            }
        }
    }
    return true;
}
function StyleChangingCheckBoxValidator_Verify(control) {
    var controlToValidate = document.getElementById(control.controltovalidate);
    if (controlToValidate != null) {
        var controlToChange = document.getElementById(control.controltochange);

        if (control.enabled == "False") {
            // If not already invalid; toggle css class
            if (IsValid(control.controltovalidate)) {
                controlToChange.attributes['class'].value = control.originalcssclass;
            }
            return true;
        }

        if (controlToValidate.checked == false) {
            controlToChange.attributes['class'].value = control.changecssclass;
            return false;
        }
        else {
            // If not already invalid; toggle css class
            if (IsValid(control.controltovalidate)) {
                controlToChange.attributes['class'].value = control.originalcssclass;
            }
            return true;
        }
    }
}
function StyleChangingCustomValidator_Verify(control) {

    var controlToValidate = document.getElementById(control.controltovalidate);
    if (controlToValidate != null) {
        var controlToChange = document.getElementById(control.controltochange);
        var clientValidationFunction = control.clientvalidationfunction;
        var isValid;
        eval("isValid = " + clientValidationFunction + "('" + control.controltovalidate + "');");
        if (isValid == false) {
            controlToChange.attributes['class'].value = control.changecssclass;
            return false;
        }
        else {
            // If not already invalid; toggle css class
            if (IsValid(control.controltovalidate)) {
                controlToChange.attributes['class'].value = control.originalcssclass;
            }
            return true;
        }
    }
    return true;
}

function StyleChangingMaxLengthValidator_Verify(control) {

    var controlToValidate = document.getElementById(control.controltovalidate);

    if (controlToValidate != null) {
        if (controlToValidate.tagName == "INPUT" || controlToValidate.tagName == "TEXTAREA") {
            var maxLength = parseInt(control.maxlength);
            var controlToChange = document.getElementById(control.controltochange);
            if (controlToValidate.value.length > maxLength) {
                controlToChange.attributes['class'].value = control.changecssclass;
                return false;
            }
            else {
                // If not already invalid; toggle css class
                if (IsValid(control.controltovalidate)) {
                    controlToChange.attributes['class'].value = control.originalcssclass;
                }
                return true;
            }
        }
    }
    return true;
}

function StyleChangingDateOfBirthSelectorValidator_Verify(control) {
    var controlToValidate = document.getElementById(control.controltovalidate);
    if (controlToValidate != null) {
        var controlToChange = document.getElementById(control.controltochange);
        var ddlDay = document.getElementById(control.controltovalidate + "_ddlDay");
        var ddlMonth = document.getElementById(control.controltovalidate + "_ddlMonth");
        var ddlYear = document.getElementById(control.controltovalidate + "_ddlYear");

        var day = parseInt(ddlDay.options[ddlDay.selectedIndex].value);
        var month = parseInt(ddlMonth.options[ddlMonth.selectedIndex].value);
        var year = parseInt(ddlYear.options[ddlYear.selectedIndex].value);

        var isValid = (day > 0 && year > 0 && (day <= [, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (day == 29 && month == 2 && year % 4 == 0 && (year % 100 > 0 || year % 400 == 0))));

        if (!isValid) {
            controlToChange.attributes['class'].value = control.changecssclass;
            return false;
        }
        else {
            // If not already invalid; toggle css class
            if (IsValid(control.controltovalidate)) {
                controlToChange.attributes['class'].value = control.originalcssclass;
            }
            return true;
        }
    }
}

function toUppercase(clientId) {
    var el = document.getElementById(clientId);
    el.value = el.value.toUpperCase();
}
