// File Pandorion.js - Primary JavaScript file for the Pandorion web site
//
// Set constants for colours
var linkBg      = '#22511D';
var linkBorder  = '#81A11D';
var hoverBg     = '#81A11D';
var hoverBorder = '#22511D';
var formTextEnabled  = '#22511D';
var formTextDisabled = '#A0C8A0';

// Get user's screen resolution
var sWidth = screen.availWidth;
var sHeight = screen.availHeight;

// Set position values for page components
var ntLeft = 0;     /* Navigation table. Everything else is based on this. */
var ntTop = 0;      /*    Distance from top */
var ntWidth = 120;  /*    Width of the table */
var ntHeight = 20;  /*    Height of each entry */
var ntGap = 0;      /*    Spacing between enries */

var ndLeft = ntLeft + ntWidth;  /* Navigation descriptions. Attached to each entry in the navigation table */
var ndTop = ntTop + ntGap;

// Internet Explorer calculates some offsets differently, so make adjustments
var client = 'ALL';
if (navigator.appName.indexOf('Microsoft') != -1) {
    client = 'IE';
    ntGap = ntGap + 2;
    ntHeight = ntHeight + 2;
}
createCookie('PandorionBrowserType', client, 30);
// redisplay - redisplay the document using a different query string
function redisplay(qString) {
    var s = new String(window.location);
    var q = s.indexOf('?') + 1;
    if (q >= 0) {
        var t = s.substr(0, q) + qString;
        window.location.replace(t);
    }
}
// hover - change the background colour
function hover(id) {
    var obj = document.getElementById(id);
    obj.style.backgroundColor = hoverBg;
    obj.style.borderColor = hoverBorder;
}
// noHover - change the background colour
function noHover(id) {
    var obj = document.getElementById(id);
    obj.style.backgroundColor = linkBg;
    obj.style.borderColor = linkBorder;
}
// showMenuText - set visibility on for a menu information item
function showMenuText(id, num) {
    var obj = document.getElementById(id);
    var i = ndTop + ((num - 1) * (ntHeight + ntGap));
    obj.style.top = i + 'px';
    obj.style.left = ndLeft + 'px';
    showItem(id);
}
// hideMenuText - set visibility off for a menu information item
function hideMenuText(id) {
    hideItem(id);
}
// showItem - set visibility on for any item
function showItem(id) {
    document.getElementById(id).style.visibility = 'visible';
}
// hideItem - set visibility off
function hideItem(id) {
    document.getElementById(id).style.visibility = 'hidden';
}
// beadTypeChanged - driven when a selection is made in the drop-down list of bead types
function beadTypeChanged(selectField) {
    var newSize = beadSize[selectField.selectedIndex];
    var newSizeText = beadSizeText[selectField.selectedIndex];
    setSize(newSize, newSizeText);
}
// setSize - change the highlighting of the bead size fields
function setSize(newSize, sizeText) {
    document.getElementById('sizeType').value = newSize;
    var sizeSet = '';
    var sizeSetter = '';
    if (newSize > 0) {
        sizeSetter = 'sizeSet = sizeControl' + newSize + 'a + sizeText + sizeControl' + newSize + 'b';
        eval(sizeSetter);
    }
    document.getElementById('sizeTable').innerHTML = sizeSet;
    if (newSize > 0) {
        document.getElementById('sizeNumber').value = '';
    }
}
// checkBeadSearch - check the fields entered on the bead search form
function checkBeadSearch() {
    var valid = true;
    if (document.getElementById('sizeType').value == 2) {
        valid = checkSize();
    }
    return valid;
}
// checkFindingSearch - check the fields entered on the finding search form
function checkFindingSearch() {
    return checkSize();
}
// checkSize - check the contents of the bead or finding size entry field
function checkSize() {
    var sizeRequested = trim(document.getElementById('sizeNumber').value);
    var valid = checkNumeric(sizeRequested);
    if (!valid) {
        alert('Please note: only numbers can be entered for the size');
    }
    return valid;
}
// checkNumeric - check that a field contains valid numbers
function checkNumeric(numValue) {
    var valid = true;
    var trimValue = trim(numValue);
    if (numValue.length > 0) {
        for (var i = 0; i < numValue.length; i++) {
            if ((numValue.charAt(i) < '0') || (numValue.charAt(i) > '9')) {
                valid = false;
                break;
            }
        }
    }
    return valid;
}
// trim - remove all spaces from both ends of a string
function trim(inString) {
    var outString = trimRight(trimLeft(inString));
    return outString;
}
// trimLeft - remove all spaces on the left of a string
function trimLeft(inString) {
    var outString = inString.replace(/[ ]*/, '');
    return outString;
}
// trimRight - remove all spaces on the right of a string
function trimRight(inString) {
    var outString = inString.replace(/[ ]*$/, '');
    return outString;
}
// saveScroll - save the current scroll coordinates
function saveScroll(form) {
    var x = 0, y = 0;
    if (typeof(window.pageXOffset) == 'number') {
        x = window.pageXOffset;
        y = window.pageYOffset;
    }
    else {
        if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            x = document.body.scrollLeft;
            y = document.body.scrollTop;
        }
        else {
            if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
                x = document.documentElement.scrollLeft;
                y = document.documentElement.scrollTop;
            }
        }
    }
    var getx = 'document.' + form + '.xpos.value = x';
    var gety = 'document.' + form + '.ypos.value = y';
    eval(getx);
    eval(gety);
}
// submitForm - submit one of the 'add' or 'change' forms
function submitForm(form, process) {
    saveScroll(form);
    var stmt = 'var numFields = document.' + form + '.length';
    eval(stmt);
    stmt = 'var link = document.' + form + '.action';
    eval(stmt);
    var delim = '?';
    for (var i = 0; i < numFields; i++) {
        stmt = 'var field = document.' + form + '.elements[i]';
        eval(stmt);
        link += delim + field.name + '=' + field.value;
        delim = '&';
    }
    link += delim + 'process=' + process;
    window.location.replace(link);
}
// setTableWidth - set the width of one or more tables.
// Assuming setClass="Alignment", all tables with class="Alignment" will have their width reset to the maximum width of all "Alignment" tables and the
// table with an id of matchId. Also, tables with class="Alignment2" will be set to the same width, but they don't come into the maximum calculation.
function setTableWidth(setClass, matchId) {
    var m = 0;
    var tables = document.getElementsByClassName(setClass, 'table');
    for (var i = 0; i < tables.length; i++) {
        m = Math.max(m, tables[i].clientWidth);
    }
    var matchTab = document.getElementById(matchId);
    if (matchTab != null) {
        m = Math.max(m, matchTab.clientWidth);
    }
    if (m > 0) {
        for (var i = 0; i < tables.length; i++) {
            tables[i].setAttribute('width', m);
        }
        var setClass2 = setClass + '2';
        tables = document.getElementsByClassName(setClass2, 'table');
        if (tables.length > 0) {
            for (var i = 0; i < tables.length; i++) {
                 tables[i].setAttribute('width', m);
            }
        }
    }

}
// Get all elements in the document that match a certain class name and optional tag type
document.getElementsByClassName = function(thisClass, tagType) {
    var tag = '*';
    if (tagType != null) {
        tag = tagType;
    }
    var retElements = new Array();
    var elem = document.getElementsByTagName(tag);
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].className == thisClass) {
            retElements.push(elem[i]);
        }
    }
    return retElements;
};
// emailCheck - validate an email address entered into a form
function emailCheck(str) {
    var valid = true;
    var at = '@';
    var dot = '.';
    var lat = str.indexOf(at);
    var lstr = str.length - 1;
    var ldot = str.indexOf(dot);
    if (str.indexOf(at) == -1) {
       valid = false;
    }
    if (valid) {
        if (str.indexOf(at) == -1 || str.indexOf(at) == 0 || str.indexOf(at) == lstr) {
            valid = false;
        }
    }
    if (valid) {
        if (str.indexOf(dot) == -1 || str.indexOf(dot) == 0 || str.indexOf(dot) == lstr) {
            valid = false;
        }
    }
    if (valid) {
        if (str.indexOf(at, (lat+1)) != -1) {
            valid = false;
        }
    }
    if (valid) {
        if (str.substring(lat-1, lat) == dot || str.substring(lat+1, lat+2) == dot) {
            valid = false;
        }
    }
    if (valid) {
        if (str.indexOf(dot, (lat+2)) == -1) {
            valid = false;
        }
    }
    if (valid) {
        if (str.indexOf(" ") != -1) {
            valid = false;
        }
    }
    if (!valid) {
        alert('The email address is not correct');
    }
    return valid;
}
// checkCustomerExisting - check email address entered on the existing customer form
function checkCustomerExisting() {
    var valid = true;
    var ea = document.getElementById('emailAddress').value;
    valid = emailCheck(ea);
    return valid;
}
// checkCustomerNew - check email details entered on the new customer form
function checkCustomerNew() {
    var valid = true;
    var e1 = document.getElementById('email1').value;
    var e2 = document.getElementById('email2').value;
    var p1 = document.getElementById('password1').value;
    var p2 = document.getElementById('password2').value;
    if (e1.length == 0) {
        alert('Please enter an email address');
        valid = false;
    }
    if (valid) {
        if (e1 != e2) {
            alert('You must enter the same email address twice as a confirmation');
            valid = false;
        }
    }
    if (valid) {
        if (p1.length == 0) {
            alert('Please enter a password');
            valid = false;
        }
    }
    if (valid) {
        if (p1 != p2) {
            alert('You must enter the same password twice as a confirmation');
            valid = false;
        }
    }
    if (valid) {
        valid = emailCheck(e1);
    }
    return valid;
}
// checkPasswordChange - check passwords entered on the password change form
function checkPasswordChange() {
    var valid = true;
    var p0 = document.getElementById('up').value;
    var p1 = document.getElementById('password1').value;
    var p2 = document.getElementById('password2').value;
    if (p0.length == 0) {
        alert('Please enter your current password');
        valid = false;
    }
    if (valid) {
        if (p1.length == 0) {
            alert('Please enter a new password');
            valid = false;
        }
    }
    if (valid) {
        if (p1 != p2) {
            alert('You must enter the same new password twice as a confirmation');
            valid = false;
        }
    }
    return valid;
}
// createCookie - create a cookie
function createCookie(name, value, days) {
    var cookie = name + '=' + value + '; expires=';
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    cookie += date.toGMTString() + ';';
    cookie += ' path=/';
    document.cookie = cookie;
}