if (window.addEventListener) { 
window.addEventListener('load', showGlobalMessage, false); 
} else if (window.attachEvent) { 
window.attachEvent('onload', showGlobalMessage); 
} 

// Form validation -------------------------------------------------------------------------------------

function runForm()
{
    document.getElementById("theform").submit();
}    

function setGlobalAction(val)
{
    document.getElementById("globalAction").value = val;
}    

function setGlobalId(val)
{
    document.getElementById("globalId").value = val;
} 

function checkLive(evt,checkFor) 
{ 
// onkeypress="return checkInput(event)"

//checkFor 1 = [a-zA-Z]

    var re = /[a-zA-Z0-9_-]/

    if (checkFor == 1) { //URL proof text
    re = /[a-zA-Z0-9_-]/
    } else if (checkFor == 2) { //Only numbers
    re = /[0-9]/
    } else if (checkFor == 3) { //Email
    re = /[(.)(@)a-zA-Z0-9_-]/
    } else if (checkFor == 4) { //Mobile number
    re = /[0-9+]/
    }

    var charCode = (evt.which) ? evt.which : window.event.keyCode; 
 
    if (charCode <= 13) 
    { 
        return true; 
    } 
    else 
    { 
        var keyChar = String.fromCharCode(charCode); 
        return re.test(keyChar); 
    } 
}

function isDate(dateStr) {

//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
var datePat = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/;
var matchArray = dateStr.match(datePat); // is the format ok?

if (matchArray == null) {
//alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
return false;
}

//month = matchArray[1]; // p@rse date into variables
//day = matchArray[3];
//year = matchArray[5];

year = matchArray[1];
month = matchArray[3]; // p@rse date into variables
day = matchArray[5];

if (month < 1 || month > 12) { // check month range
//alert("Month must be between 1 and 12.");
return false;
}

if (day < 1 || day > 31) {
//alert("Day must be between 1 and 31.");
return false;
}

if ((month==4 || month==6 || month==9 || month==11) && day==31) {
//alert("Month "+month+" doesn`t have 31 days!")
return false;
}

if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day > 29 || (day==29 && !isleap)) {
//alert("February " + year + " doesn`t have " + day + " days!");
return false;
}
}
return true; // date is valid
}

function limitText(obj, maxchars)
{
	var labelname = obj.id + 'Counter';

	if (obj.value.length > maxchars)
	{
		obj.value = obj.value.substr(0, maxchars);
		
	}

	var counter = document.getElementById(labelname);
	if (navigator.userAgent.indexOf('Gecko') >= 0)
		counter.innerHTML = obj.value.length;
	else
		counter.innerText = obj.value.length;
}


// Global ----------------------------------------------------------------------------------------------

function layer(layerId,inputId)
{
    if(document.getElementById(layerId).style.display != "block") {
        document.getElementById(layerId).style.display = "block";
        if(document.getElementById(inputId) != null) {
            document.getElementById(inputId).focus();
        }
    } else {
        if(document.getElementById(inputId) != null) {
            document.getElementById(inputId).blur();
        }    
        document.getElementById(layerId).style.display = "none";
    }
}   

function link(url)
{
    window.location.href = url;
}

function getObjectPos(obj)
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function getObjectSize(obj) 
{
    var objectWidth = obj.offsetWidth;
    var objectHeight = obj.offsetHeight;
    
    return [objectWidth,objectHeight];
}

function getScrollPos()
{
    var position = [0, 0];
    if (typeof window.pageYOffset != 'undefined') {
        position = [
        window.pageXOffset,
        window.pageYOffset
        ];
    } else if (typeof document.documentElement.scrollTop != 'undefined') {
        position = [
        document.documentElement.scrollLeft,
        document.documentElement.scrollTop
        ];
    } else if (typeof document.body.scrollTop != 'undefined') {
        position = [
        document.body.scrollLeft,
        document.body.scrollTop
        ];
    }

    return position;
}

function getBrowserSize()
{
    var size = [0, 0];

    if (self.innerHeight) { // all except Explorer
        size = [
        self.innerWidth,
	    self.innerHeight
	    ];
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	    size = [
	    document.documentElement.clientWidth,
	    document.documentElement.clientHeight
	    ];
	} else if (document.body) { // other Explorers
	    size = [
	    document.body.clientWidth,
	    document.body.clientHeight
	    ];
	}
	
    return size;	
}

function getCursorPos(e)
{
    e = (e) ? e : window.event;

	//Get scroll position
	var scrollPos = getScrollPos();

    var position = [0, 0];

    if(e.pageX) {
        position = [
		e.pageX,
		e.pageY
		];
	} else if(e.clientX) {
	    position = [
		e.clientX + scrollPos[0], //If IE add scrollX position
		e.clientY + scrollPos[1] //If IE add scrollY position
		];
	} 

    return position;	
}

function getPageSizeWithScroll()
{     
    if (window.innerHeight && window.scrollMaxY) { // Firefox         
        yWithScroll = window.innerHeight + window.scrollMaxY;         
        xWithScroll = window.innerWidth + window.scrollMaxX;     
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac         
        yWithScroll = document.body.scrollHeight;         
        xWithScroll = document.body.scrollWidth;     
    } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari         
        yWithScroll = document.body.offsetHeight;         
        xWithScroll = document.body.offsetWidth;       
    }     
    
    arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);     
    //alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );     
    return arrayPageSizeWithScroll; 
}


// FADE effects --------------------------------------------------------------------------------------------

// #### Opacity ####

function opacityGlobal(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i--) {
            setTimeout("changeOpacGlobal(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i++)
            {
            setTimeout("changeOpacGlobal(" + i + ",'" + id + "')",(timer * speed));
            timer++;
        }
    }
}

//change the opacity for different browsers
function changeOpacGlobal(opacity, id) { 
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
} 



// GLOBAL INFO --------------------------------------------------------------------------------------------

function showGlobalHoverInfo(e,infoText)
{
// onmouseover="showGlobalHoverInfo(event,'<%=StringHandling.JavascriptSafe(string.Format(Global.Translate("POP_WhatIsUserNameDoing"), strUserName))%>');" onmouseout="hideGlobalHoverInfo();" 
    
    var globalHoverInfo = document.getElementById("globalHoverInfo");
    var globalHoverInfoText = document.getElementById("globalHoverInfoText");
    globalHoverInfoText.innerHTML = infoText //Set info text
    globalHoverInfo.style.display = "block";
    
    //Get size of globalHoverInfo
    var divWidth = globalHoverInfo.offsetWidth;
    var divHeight = globalHoverInfo.offsetHeight;
    
    //Get cursor position
    var cursorPos = getCursorPos(e);  
	
	//Get browser size
	var browserSize = getBrowserSize();
	
	//Position globalHoverInfo
	var divPosX = Math.round(cursorPos[0]-(divWidth/2));
	var divPosY = Math.round(cursorPos[1]-(divHeight+15));
	globalHoverInfo.style.left = divPosX+"px";
	globalHoverInfo.style.top = divPosY+"px";   

} 

function hideGlobalHoverInfo() 
{
    var globalHoverInfo = document.getElementById("globalHoverInfo");
    var globalHoverInfoText = document.getElementById("globalHoverInfoText");
    globalHoverInfo.style.display = "none";
    globalHoverInfoText.innerHTML = "";
}


// GLOBAL MESSAGE --------------------------------------------------------------------------------------------

function showGlobalMessage()
{   
    if(document.getElementById("globalMessageText") != null) {
        if(document.getElementById("globalMessageText").innerHTML.length > 0) {
            var globalMessage = document.getElementById("globalMessage");
            var globalMessageCenter = document.getElementById("globalMessageCenter");
            var pageSize = getPageSizeWithScroll();
            var browserSize = getBrowserSize();
            var scrollPos = getScrollPos();
            var blackHeight = pageSize[1];
            
            if(browserSize[1] > pageSize[1]) {
                blackHeight = browserSize[1];
            }            
            
            globalMessageCenter.style.top = scrollPos[1]+200+"px";
            globalMessage.style.height = blackHeight + "px";
            globalMessage.style.display = "block";
        }
    }
}    

function hideGlobalMessage()
{
    var globalMessage = document.getElementById("globalMessage");
    globalMessage.style.display = "none";
    
    var globalMessageFormFocus = document.getElementById("globalMessageFormFocus").value;
    
    if(globalMessageFormFocus.length > 0) {
        document.getElementById(globalMessageFormFocus).focus();
    }
    
    document.getElementById("globalMessageFormFocus").value = "";
    
//    opacityGlobal('globalMessage', 50, 0, 500);
//    setTimeout("document.getElementById('globalMessage').style.display = 'none'", 500);
}

function runGlobalMessage(text,inputIdFocus)
{
//runGlobalMessage('<%=Mix.JavascriptSafe(Global.Translate("ACCOUNT_MustSelectPicture").ToString())%>','pictureFile');
    var globalMessageText = document.getElementById("globalMessageText");
    globalMessageText.innerHTML = text;
    
    if(inputIdFocus != null) {
        document.getElementById("globalMessageFormFocus").value = inputIdFocus;
    } else {
        document.getElementById("globalMessageFormFocus").value = "";
    }      
    
    showGlobalMessage();
}





// GLOBAL STATUS --------------------------------------------------------------------------------------------

function showGlobalStatus()
{   
    if(document.getElementById("globalStatusText") != null) {
        if(document.getElementById("globalStatusText").innerHTML.length > 0) {
            var globalStatus = document.getElementById("globalStatus");
            var globalStatusCenter = document.getElementById("globalStatusCenter");
            var pageSize = getPageSizeWithScroll();
            var browserSize = getBrowserSize();
            var scrollPos = getScrollPos();
            var blackHeight = pageSize[1];
            
            if(browserSize[1] > pageSize[1]) {
                blackHeight = browserSize[1];
            }            
            
            globalStatusCenter.style.top = scrollPos[1]+200+"px";
            globalStatus.style.height = blackHeight + "px";
            globalStatus.style.display = "block";
        }
    }
}   

function runGlobalStatus(text)
{
//runGlobalStatus('<%=StringHandling.JavascriptSafe(Global.Translate("ACCOUNT_MustSelectPicture"))%>');
    var globalStatusText = document.getElementById("globalStatusText");
    globalStatusText.innerHTML = text;
         
    showGlobalStatus();
}


//IMAGE EDITING

function showRotateImage(imageObject,entryId,imageCount)
{
    var rotateImageEntryId = document.getElementById("rotateImageEntryId");
    var rotateImageImageCount = document.getElementById("rotateImageImageCount");
    rotateImageImageCount.value = imageCount;
    rotateImageEntryId.value = entryId;
    
    var objectPos = getObjectPos(imageObject);
    var objectSize = getObjectSize(imageObject);
    
    var rotateImageControl = document.getElementById("rotateImageControl");
    var rotateImageControlWidth = objectSize[0]-100; //-20 for padding
    var rotateImageControlPosLeft = objectPos[0] + 40;
    var rotateImageControlPosTop = objectPos[1]+Math.round(objectSize[1]/3);
    
    rotateImageControl.style.width = rotateImageControlWidth + "px";
    rotateImageControl.style.left = rotateImageControlPosLeft + "px";
    rotateImageControl.style.top = rotateImageControlPosTop + "px";
    
    rotateImageControl.style.display = "block";
}

function hideRotateImage(imageObject,e)
{
    var rotateImageControl = document.getElementById("rotateImageControl");
    var bHideRotateImageControl = false;
    
    var objectPos = getObjectPos(imageObject);
    var objectSize = getObjectSize(imageObject);
    
    var imageLeftBoundary = objectPos[0]+30;
    var imageRightBoundary = objectPos[0] + objectSize[0] - 30;
    var imageTopBoundary = objectPos[1] + 10;
    var imageBottomBoundary = objectPos[1] + objectSize[1] - 10;
        
    //Get cursor position
    var cursorPos = getCursorPos(e);
    
    //Check if cursor is outside imageObject
    if((cursorPos[0] < imageLeftBoundary) || (cursorPos[0] > imageRightBoundary) || (cursorPos[1] < imageTopBoundary) || (cursorPos[1] > imageBottomBoundary)) {
        bHideRotateImageControl = true;  
    }
    
    if(bHideRotateImageControl) {
        rotateImageControl.style.display = "none";
    }
}

function runRotateImage(action)
{
    document.getElementById("rotateImageAction").value = action;
    document.getElementById("form_rotateImage").submit();
}


// HOVER IMAGE start -----------------------------------------------------------------------------

function hoverImg(img)
{
    imgSrc = img.src;
    imgSrcLength = img.src.length;
    imgType = imgSrc.substring(imgSrcLength-3,imgSrcLength);
    imgState = imgSrc.substring(imgSrcLength-5,imgSrcLength-4);
    imgNewState = "1";
    
    if(imgState == "1") {
        imgNewState = "0";
    }
    
    img.src = imgSrc.replace(imgState+"."+imgType,imgNewState+"."+imgType);
}

// HOVER IMAGE end -----------------------------------------------------------------------------

// HOVER ICON start -----------------------------------------------------------------------------

function hoverIcon(icon,showHide,text)
{
    iconText = document.getElementById("topMenuIconHover");
    
    if(showHide == 0) {
        iconText.style.display = "none";
    } else {
        iconText.innerHTML = text;        
        iconText.style.display = "block";
    }
}

// HOVER ICON end -----------------------------------------------------------------------------


// SHOW HD PHOTO --------------------------------------------------------------------------------------------

//function showHd(imgUrl)
//{   
//            var globalHd = document.getElementById("globalHd");
//            var globalHdArea = document.getElementById("globalHdArea");
//            var globalHdCenter = document.getElementById("globalHdCenter");
//            var pageSize = getPageSizeWithScroll();
//            var browserSize = getBrowserSize();
//            var scrollPos = getScrollPos();
//            var blackHeight = pageSize[1]+scrollPos[1];
//            
//            if(browserSize[1] > pageSize[1]) {
//                blackHeight = browserSize[1]+scrollPos[1];
//            }            
//            
//            globalHdCenter.innerHTML = "<img src='" + imgUrl + "'>";
//            
//            globalHdCenter.style.top = scrollPos[1]+20+"px";
//            globalHdArea.style.height = blackHeight + "px";
//            globalHd.style.display = "block";
//}    

function showHd(imgUrl)
{   
            var globalHd = document.getElementById("globalHd");
            var scrollPos = getScrollPos();
     
            globalHd.innerHTML = "<img src='" + imgUrl + "'>";
            
            globalHd.style.top = scrollPos[1]+10+"px";
            globalHd.style.display = "block";
            opacityGlobal('globalHd', 0, 100, 500);
}  

function hideHd()
{   
    opacityGlobal('globalHd', 100, 0, 500);
    setTimeout("document.getElementById('globalHd').style.display = 'none'", 500);
}


function previewGrade(grade)
{
    if(grade == 0) {
        grade = document.getElementById("selectedGrade").value;
    }
        var allImages = document.getElementsByTagName("img");
        for (var i = 0; i < allImages.length; i++) { //Loop through images
            
            if(allImages[i].id.substring(0,9) == "prevGrade") {
                if(allImages[i].id.substring(9,10) <= grade) {
                    img = allImages[i];
                    imgSrc = img.src;
                    imgSrcLength = img.src.length;
                    imgType = imgSrc.substring(imgSrcLength-3,imgSrcLength);
                    imgState = imgSrc.substring(imgSrcLength-5,imgSrcLength-4);
                    imgNewState = "1";                    
                    img.src = imgSrc.replace(imgState+"."+imgType,imgNewState+"."+imgType);
    
                } else {
                    img = allImages[i];
                    imgSrc = img.src;
                    imgSrcLength = img.src.length;
                    imgType = imgSrc.substring(imgSrcLength-3,imgSrcLength);
                    imgState = imgSrc.substring(imgSrcLength-5,imgSrcLength-4);
                    imgNewState = "0";                    
                    img.src = imgSrc.replace(imgState+"."+imgType,imgNewState+"."+imgType);
                }
            }
            
        }  
}

function setGrade(grade)
{
    document.getElementById("selectedGrade").value = grade;
}    


function replyComment(sortOrder, writtenByUserId, commentId, userName)
{
    document.getElementById("replyToCommentId").value = commentId;
    var headlineText = "";
    
    if(commentId != 0) {
        document.getElementById("commentPhoto").style.display = "block";
        document.getElementById("commentText").focus();
        document.getElementById("writtenByUserId").value = writtenByUserId;
        document.getElementById("sortOrder").value = sortOrder;
        document.getElementById("replyToInfoText").innerHTML = document.getElementById("resetReplyToInfo").value.replace("{0}",userName);
        document.getElementById("gradeSelecter").style.display = "none";
        headlineText = document.getElementById("commentPictureText").value;
    } else {
        document.getElementById("gradeSelecter").style.display = "block";
        headlineText = document.getElementById("commentAndGradePictureText").value;
    }
    
    document.getElementById("commentPhotoHeadline").innerHTML = headlineText;
}

function previewCommentColors()
{
    var target = document.getElementById("commentText");
    
    target.style.background = "#" + document.getElementById("commentBackgroundColor").value;
    target.style.color = "#" + document.getElementById("commentTextColor").value;
}


// UPLOAD PICTURE ----------------------------------------


function enableDisableDate()
{
    var year = document.getElementById("year");
    var month = document.getElementById("month");
    var day = document.getElementById("day");

    if(document.getElementById("autoDate").checked) {
        year.disabled = true; 
        month.disabled = true;
        day.disabled = true;
    } else {
        year.disabled = false; 
        month.disabled = false;
        day.disabled = false;
    }
}


// SETTINGS 

function settingsPersonalInfo()
{
    var settingsForPersonalInfo = document.getElementById("settingsForPersonalInfo");
    
    if(document.getElementById("showPersonalInfo").checked) {
        settingsForPersonalInfo.style.display = "block";
    } else {
        settingsForPersonalInfo.style.display = "none";
    }
}

function settingsPersonalPresentation()
{
    var settingsForPersonalPresentation = document.getElementById("settingsForPersonalPresentation");
    
    if(document.getElementById("showPersonalPresentation").checked) {
        settingsForPersonalPresentation.style.display = "block";
    } else {
        settingsForPersonalPresentation.style.display = "none";
    }
}

function settingsCopyright()
{
    var settingsForCopyright = document.getElementById("settingsForCopyright");
    
    if(document.getElementById("copyrightPictures").checked) {
        settingsForCopyright.style.display = "block";
    } else {
        settingsForCopyright.style.display = "none";
    }
}

function setTypeOfStamp(val)
{
    document.getElementById("stamp1").style.display = "none";
    document.getElementById("stamp2").style.display = "none";
    document.getElementById("previewStamp1").style.display = "none";
    document.getElementById("previewStamp2").style.display = "none";
    
    document.getElementById("stamp" + val).style.display = "block";
    document.getElementById("previewStamp" + val).style.display = "block";
}

function previewCopyrightText()
{
    var text = document.getElementById("copyrightText").value;
    var size = document.getElementById("copyrightTextSize").value + "pt";
    var font = document.getElementById("copyrightTextFont").value;
    
    document.getElementById("previewStamp1").innerHTML = text;
    document.getElementById("previewStamp1").style.fontSize = size;
    document.getElementById("previewStamp1").style.fontFamily = font;
}


//CHECK PASSWORD --------- START --------------------------------------

var commonPasswords = new Array('password', 'pass', '1234', '1246'); 
 
var numbers = "0123456789"; 
var lowercase = "abcdefghijklmnopqrstuvwxyz"; 
var uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
var punctuation = "!.@$£#*()%~<>{}[]"; 
 
function checkPassword(password, stableName) { 
 
    var combinations = 0; 
 
    if (contains(password, numbers) > 0) { 
        combinations += 10; 
    } 
 
    if (contains(password, lowercase) > 0) { 
        combinations += 26; 
    } 
 
    if (contains(password, uppercase) > 0) { 
        combinations += 26; 
    } 
 
    if (contains(password, punctuation) > 0) { 
        combinations += punctuation.length; 
    } 
 
    // work out the total combinations 
    var totalCombinations = Math.pow(combinations, password.length); 
 
    // if the password is a common password, then everthing changes... 
    if (isCommonPassword(password)) { 
        totalCombinations = 75000 // about the size of the dictionary 
    } 
    
    // if password and username are the same
    if (password == stableName) {
        totalCombinations = 1;
    }
 
    // work out how long it would take to crack this (@ 200 attempts per second) 
    var timeInSeconds = (totalCombinations / 200) / 2; 
 
    // this is how many days? (there are 86,400 seconds in a day. 
    var timeInDays = timeInSeconds / 86400 
 
    // how long we want it to last 
    var lifetime = 365; 
 
    // how close is the time to the projected time? 
    var percentage = timeInDays / lifetime; 
 
    var friendlyPercentage = cap(Math.round(percentage * 100), 100); 
    if (totalCombinations != 75000 && friendlyPercentage < (password.length * 5)) { 
        friendlyPercentage += password.length * 5; 
    } 
 
    var progressBar = document.getElementById("progressBar"); 
    progressBar.style.width = friendlyPercentage + "%"; 
 
    var passwordValid = document.getElementById("passwordValid"); 
    passwordValid.value = "0";
 
    if (percentage > 1) { 
        // strong password 
        progressBar.style.backgroundColor = "#73ac1a"; 
        passwordValid.value = "1";
        return; 
    } 
 
    if (percentage > 0.5) { 
        // reasonable password 
        progressBar.style.backgroundColor = "#ffd700"; 
        return; 
    } 
 
    if (percentage > 0.10) { 
        // weak password 
        progressBar.style.backgroundColor = "#ff7200"; 
        return; 
    } 
 
    // useless password! 
    if (percentage <= 0.10) { 
        // weak password 
        progressBar.style.backgroundColor = "#ff0086"; 
        return; 
    } 
 
 
} 
 
function cap(number, max) { 
    if (number > max) { 
        return max; 
    } else { 
        return number; 
    } 
} 
 
function isCommonPassword(password) { 
 
    for (i = 0; i < commonPasswords.length; i++) { 
        var commonPassword = commonPasswords[i]; 
        if (password == commonPassword) { 
            return true; 
        } 
    } 
 
    return false; 
 
} 
 
function contains(password, validChars) { 
 
    count = 0; 
 
    for (i = 0; i < password.length; i++) { 
        var char = password.charAt(i); 
        if (validChars.indexOf(char) > -1) { 
            count++; 
        } 
    } 
 
    return count; 
} 

//CHECK PASSWORD --------- END --------------------------------------
