// Custom variable declarations
var doNotFadeNotification = false;
var stickyNotification = false;
var fadeNotification = false;
var busyFadingIn = false;
var stringForMethodToCallOnReturn = "";
var stringForMethodToCallOnEscape = "";
var keyDebt = 0;

// Make some declarations to the document
document.onkeyup = KeyCheck;

// Custom AJAX methods
function newPostAJAXRequestWithURL(url) {
    request = false;
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			request = new XMLHttpRequest();
        } catch(e) {
			request = false;
        }
    } else if(window.ActiveXObject) {
       	try {
        	request = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		request = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		request = false;
        	}
		}
    };
    request.open("POST", url, true);
    return request;
}

function newGetAJAXRequestWithURL(url) {
    request = false;
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			request = new XMLHttpRequest();
        } catch(e) {
			request = false;
        }
    } else if(window.ActiveXObject) {
       	try {
        	request = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		request = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		request = false;
        	}
		}
    };
    request.open("GET", url, true);
    return request;
}

function processQuantityChangeRequest() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            // No error
            document.getElementById("totalCell").innerHTML = "<b>Subtotal:</b> $" + request.responseText;
        } else {
            alert("There was a problem recieving your updated subtotal from the server.  The amount you see in your browser may not be accurate.");
        }
    };
}

function addOneQuantityForCatalogNumber(catalog_num) {
    document.getElementById(catalog_num).value = parseInt(document.getElementById(catalog_num).value) + 1;
    manuallyChangeQuantityForCatalogNumber(catalog_num);
}

function subtractOneQuantityForCatalogNumber(catalog_num) {
    document.getElementById(catalog_num).value = parseInt(document.getElementById(catalog_num).value) - 1;
    manuallyChangeQuantityForCatalogNumber(catalog_num);
}

function refreshTableRowColoring(hilightHex) {
    var rows = document.getElementById('theTable').getElementsByTagName('div');
    for (i = 0; i < rows.length; i++) {
        rows[i].classname = "";
        rows[i].style.backgroundColor = "#FFFFFF";
        if ((i-1)%2 == 0 && i < rows.length-2) {
            rows[i].className = "hilighted";
            rows[i].style.backgroundColor = "#" + hilightHex;
        };
    };
}

function refreshTableRowColoringWithRGB(hilightRGB) {
    var rows = document.getElementById('theTable').getElementsByTagName('div');
    for (i = 0; i < rows.length; i++) {
        rows[i].classname = "";
        rows[i].style.backgroundColor = "#FFFFFF";
        if ((i-1)%2 == 0 && i < rows.length-2) {
            rows[i].className = "hilighted";
            rows[i].style.backgroundColor = hilightRGB;
        };
    };
}

function addProductToCart(catalog_num) {
    // Add the item to the cart in the database
    var request = newGetAJAXRequestWithURL('/cart/updateCart.php?operation=add&catalog_num=' + catalog_num);
    request.onreadystatechange = processAddProductRequest;
    request.send('');
    
    // Switch the icon to 'cart_remove'
    document.getElementById(catalog_num).innerHTML = "<a href=\"javascript:removeProductFromCart('" + catalog_num + "');\">\n<img src=\"../cart/cart_delete.png\" border=\"0\">\n</a>";

}

function processAddProductRequest() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            // No error
            var catalog_num = request.responseText.split(" ")[0];
            var positionX = findPosX(document.getElementById(catalog_num));
            var positionY = findPosY(document.getElementById(catalog_num));
            document.getElementById("notification").style.opacity = 0;
            setTimeout("raiseNotificationOpacity('0', 0.08, '10')", 100);
            document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
            document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
            document.getElementById("notification").innerHTML = request.responseText;
            setTimeout("lowerNotificationOpacity('1', 0.08, '10')", 2000);
        } else {
            alert("There was a problem retrieving the data:\n" +
                request.statusText);
        }
    };
}

function manuallyChangeQuantityForCatalogNumber(catalog_num) {
    if (parseInt(document.getElementById(catalog_num).value) <= 0) {
        document.getElementById(catalog_num).value = '0';
    };
    var request = newGetAJAXRequestWithURL("/cart/updateCart.php?catalog_num=" + catalog_num + "&quantity=" + document.getElementById(catalog_num).value);
    request.onreadystatechange = processQuantityChangeRequest;
    request.send('');
    if (parseInt(document.getElementById(catalog_num).value) <= 0) {
        confirmRemoveProductFromCartInCartPage(document.getElementById(catalog_num));
    } else {
        doNotRemoveFromCart();
    };
}

function removeProductFromCart(catalog_num) {
    // Add the item to the cart in the database
    var request = newGetAJAXRequestWithURL('/cart/updateCart.php?operation=confirmDelete&catalog_num=' + catalog_num);
    request.onreadystatechange = processRemoveProductRequest;
    request.send('');
}

function processRemoveProductRequest() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            var catalog_num = request.responseText.split(" ")[5];
            var positionX = findPosX(document.getElementById(catalog_num));
            var positionY = findPosY(document.getElementById(catalog_num));
            document.getElementById("notification").style.opacity = 0;
            setTimeout("raiseNotificationOpacity('0', 0.2, '3')", 100);
            document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
            document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
            document.getElementById("notification").innerHTML = request.responseText;
            stickyNotification = true;
            stringForMethodToCallOnEscape = "doNotRemoveFromCart()";
            stringForMethodToCallOnReturn = "removeCatalogNumberFromCart('" + catalog_num + "')";
        } else {
            alert("There was a problem retrieving the data:\n" +
                request.statusText);
        }
    };
}

function raiseNotificationOpacity(opacity, opacityStepSize, timeoutStepSize) {
    if (fadeNotification == false) {
        busyFadingIn = true;
        if (opacity == '') {
            opacity = document.getElementById("notification").style.opacity;
        };
        document.getElementById("notification").style.opacity = opacity;
        var msOpacity = parseFloat(opacity) * 100;
        document.getElementById("notification").style.filter = "alpha(opacity=" + msOpacity + ");"
        var newOpacity = (parseFloat(opacity) + parseFloat(opacityStepSize));
        var timeoutString = "raiseNotificationOpacity('" + newOpacity + "', '" + opacityStepSize + "', '" + timeoutStepSize + "')";
        if (parseFloat(newOpacity) <= 1) {
            setTimeout(timeoutString, timeoutStepSize);
        } else {
            busyFadingIn = false;
        };
    };
}

function lowerNotificationOpacity(opacity, opacityStepSize, timeoutStepSize) {
    if (stickyNotification == false && busyFadingIn == false) {
        if (opacity == '') {
            opacity = document.getElementById("notification").style.opacity;
        };
        document.getElementById("notification").style.opacity = opacity;
        var msOpacity = parseFloat(opacity) * 100;
        document.getElementById("notification").style.filter = "alpha(opacity=" + msOpacity + ");"
        var newOpacity = (parseFloat(opacity) - parseFloat(opacityStepSize));
        var timeoutString = "lowerNotificationOpacity('" + newOpacity + "', '" + opacityStepSize + "', '" + timeoutStepSize + "')";
        if (fadeNotification == true) {
            stickyNotification = false;
            doNotFadeNotification = false;
        };
        if (parseFloat(newOpacity) > 0 && doNotFadeNotification == false) {
            setTimeout(timeoutString, timeoutStepSize);
        };
        if (parseFloat(newOpacity) < 0) {
            document.getElementById("notification").style.left = -10000 + "px";
            fadeNotification = false;
            stickyNotification = false;
            doNotFadeNotification = false; // reset the global variables, just to be on the safe side
            stringForMethodToCallOnEscape = ""; // Make the key bindings are ineffectual
            stringForMethodToCallOnReturn = ""; // Make the key bindings are ineffectual
        };
    };
}

function doNotRemoveFromCart() {
    stickyNotification = false;
    fadeNotification = true;
    lowerNotificationOpacity('1', 0.1, '8');
}

function removeCatalogNumberFromCart(catalog_num) {
    var delRequest = newGetAJAXRequestWithURL("/cart/updateCart.php?catalog_num=" + catalog_num + "&quantity=0");
    delRequest.onreadystatechange = doNotRemoveFromCart; // Just hides the popup box
    delRequest.send('');

    //Switch the icon to 'cart_add'
    document.getElementById(catalog_num).innerHTML = "<a href=\"javascript:addProductToCart('" + catalog_num + "');\">\n<img src=\"../cart/cart_add.png\" border=\"0\">\n</a>";
}

function confirmRemoveProductFromCartInCartPage(sender) {
    var catalog_num;
    if (sender.nodeName == "INPUT") {
        catalog_num = sender.id;
        keyDebt = 1;
    } else {
        catalog_num = sender;
    };
    var positionX = findPosX(document.getElementById(catalog_num));
    var positionY = findPosY(document.getElementById(catalog_num));
    document.getElementById("notification").style.opacity = 0;
    setTimeout("raiseNotificationOpacity('0', 0.08, '10')", 100);
    document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
    document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
    document.getElementById("notification").innerHTML = "Are you sure you want to delete " + catalog_num + " from your order?<br /><a href=\"javascript:removeCatalogNumberFromCartInCartPage('" + catalog_num + "');\">Yes</a> | <a href=\"javascript:doNotRemoveFromCartInCartPage('" + catalog_num + "');\">No</a>";
    stringForMethodToCallOnEscape = "doNotRemoveFromCartInCartPage('" + catalog_num + "')";
    stringForMethodToCallOnReturn = "removeCatalogNumberFromCartInCartPage('" + catalog_num + "')";
    stickyNotification = true;
}

function doNotRemoveFromCartInCartPage(catalog_num) {
    document.getElementById(catalog_num).value = "1";
    var request = newGetAJAXRequestWithURL('/cart/updateCart.php?catalog_num=' + catalog_num + '&quantity=' + document.getElementById(catalog_num).value);
    request.onreadystatechange = processQuantityChangeRequest;
    request.send('');
    doNotRemoveFromCart();
}

function removeCatalogNumberFromCartInCartPage(catalog_num) {
    // Make the row shrink down, then remove it from the table
    rowID = "row_" + catalog_num;
    doNotRemoveFromCart();
    refreshTableRowColoring('FCEEF1'); // Make sure all our rows have pretty pink colors
    fadeCartTableToWhite('', '30');
    lowerObjectOpacity(rowID, '1', '0.1', '30');
}

function fadeCartTableToWhite(currentHilight, timeoutStepSize) {
    if (currentHilight == "") {
        // Figure out the current hilight color
        var rows = document.getElementById('theTable').getElementsByTagName('div');
        for (i = 0; i < rows.length; i++) {
            if (rows[i].style.backgroundColor != "rgb(255, 255, 255)") {
                currentHilight = rows[i].style.backgroundColor;
            };
        };
        if (currentHilight == "") {
            currentHilight = "rgb(255, 255, 255)";
        };
    };
    refreshTableRowColoringWithRGB(lighterRGBStringWithDarkerRGBString(currentHilight)) // Refresh the row coloring to the next lighter color
    var timeoutString = "fadeCartTableToWhite('" + lighterRGBStringWithDarkerRGBString(currentHilight) + "', '" + timeoutStepSize + "')";
    if (currentHilight != "rgb(255, 255, 255)") {
        setTimeout(timeoutString, timeoutStepSize);
    };                
}

function lighterRGBStringWithDarkerRGBString(darkerRGBString) {
    if (darkerRGBString.substr(0,1) == '#') {
        darkerRGBString = rgbStringFromHexString(darkerRGBString);
    };
    var justValues = darkerRGBString.split("(")[1].split(")")[0];
    var valuesArray = justValues.split(", ");
    var redComponent = 255;
    if (parseInt(valuesArray[0]) < 255) {
        redComponent = parseInt(valuesArray[0]) + 1;
    }; 
    var greenComponent = 255;
    if (parseInt(valuesArray[1]) < 255) {
        greenComponent = parseInt(valuesArray[1]) + 1;
    }; 
    var blueComponent = 255;
    if (parseInt(valuesArray[2]) < 255) {
        blueComponent = parseInt(valuesArray[2]) + 1;
    }; 
    return "rgb(" + redComponent + ", " + greenComponent + ", " + blueComponent + ")";
}

function darkerRGBStringWithLighterRGBString(lighterRGBString, untilString) {
    var lighterValuesArray = lighterRGBString.split("(")[1].split(")")[0].split(", ");
    var untilValuesArray = untilString.split("(")[1].split(")")[0].split(", ");
    
    var redComponent = untilValuesArray[0];
    if (parseInt(lighterValuesArray[0]) > untilValuesArray[0]) {
        redComponent = parseInt(lighterValuesArray[0]) - 1;
    }; 
    var greenComponent = untilValuesArray[1];
    if (parseInt(lighterValuesArray[1]) > untilValuesArray[1]) {
        greenComponent = parseInt(lighterValuesArray[1]) - 1;
    }; 
    var blueComponent = untilValuesArray[2];
    if (parseInt(lighterValuesArray[2]) > untilValuesArray[2]) {
        blueComponent = parseInt(lighterValuesArray[2]) - 1;
    }; 
    
    return "rgb(" + redComponent + ", " + greenComponent + ", " + blueComponent + ")";
}

function lowerObjectOpacity(objectID, opacity, opacityStepSize, timeoutStepSize) {
    if (opacity != '') {
        document.getElementById(objectID).style.opacity = opacity;
        var newOpacity = (parseFloat(opacity) - parseFloat(opacityStepSize));
        var timeoutString = "lowerObjectOpacity('" + objectID + "', '" + newOpacity + "', '" + opacityStepSize + "', '" + timeoutStepSize + "')";
        if (parseFloat(newOpacity) >= 0) {
            setTimeout(timeoutString, timeoutStepSize);
        } else {
            document.getElementById(objectID).style.opacity = 0;
            // Right now the only object we're passing this is table rows.
            // We want to shrink them down to nothing, then delete them entirely
            shrinkTableRowFromSomethingToNothing('30', objectID, '50');                        
        };
    };
}

function shrinkTableRowFromSomethingToNothing(somethingHeight, tableRowID, timeoutStepSize) {
    document.getElementById(tableRowID).style.height=somethingHeight;
    var newHeight = parseInt(somethingHeight) - 2;
    var timeoutString = "shrinkTableRowFromSomethingToNothing('" + newHeight + "', '" + tableRowID + "', '" + timeoutStepSize + "')";
    if (parseInt(somethingHeight) > 0) {
        setTimeout(timeoutString, timeoutStepSize);
    } else {
        document.getElementById('theTable').removeChild(document.getElementById(tableRowID)); // Delete the table row entirely
        fadeInCartRowColoring('rgb(255, 255, 255)', 'rgb(252, 238, 241)', '3'); // Fade in the pink
        if (document.getElementById('theTable').children.length == 4) {
            window.location = 'http://www.stressmarq.com/cart';
        };
    };
}

function fadeInCartRowColoring(startColorRGB, endColorRGB, timeoutStepSize) {
    refreshTableRowColoringWithRGB(startColorRGB);
    if (startColorRGB != endColorRGB) {
        newStartColor = darkerRGBStringWithLighterRGBString(startColorRGB, endColorRGB);
        timeoutString = "fadeInCartRowColoring('" + newStartColor + "', '" + endColorRGB + "', '" + timeoutStepSize + "')";
        setTimeout(timeoutString, timeoutStepSize);
    };
}

function rgbStringFromHexString(hexString) {

    // Assumes a string in the format of #ABCDEF
    
    var redValue = parseInt(hexString.substr(1,2), 16);
    var greenValue = parseInt(hexString.substr(3,2), 16);
    var blueValue = parseInt(hexString.substr(5,2), 16);

    return "rgb(" + redValue + ", " + greenValue + ", " + blueValue + ")";

}

function KeyCheck(e) { // Remember to adapt this function to work with IE

   var KeyID = (window.event) ? event.keyCode : e.keyCode;

    if (parseInt(keyDebt) == 0) {
        if (KeyID == '13') {
            if (stringForMethodToCallOnReturn != "") {
                setTimeout(stringForMethodToCallOnReturn, 0);
            };
        };
        if (KeyID == '27') {
            if (stringForMethodToCallOnEscape != "") {
                setTimeout(stringForMethodToCallOnEscape, 0);
            };
        };
    } else {
        keyDebt = parseInt(keyDebt) - 1;
    };
}

// Checkout Page

function toggleBillingAddressEdit() {
    if (document.getElementById('billingAddressCheckbox').checked == false) {
        document.getElementById('billingAddressEdit').style.display = 'block';
    } else {
        document.getElementById('billingAddressEdit').style.display = 'none';
    };
    document.getElementById('billingProvinceLabel').innerHTML = document.getElementById('shipProvinceLabel').innerHTML;
}

function hilightTableRow(tableRow) {
    tableRow.style.backgroundColor='#FCEEF1';
}

function deselectTableRow(tableRow) {
    tableRow.style.backgroundColor='#FFFFFF';

    // We're also going to check for all required fields being filled in here
    var submittable = (document.getElementById('shipRecipient').value != '' && document.getElementById('shipCompany').value != '' && document.getElementById('shipAddress').value != '' &&     document.getElementById('shipCity').value != '' &&     document.getElementById('shipProvince').value != '' && document.getElementById('shipCountry').value != '' && 
document.getElementById('shipPostal').value != '');

    if (document.getElementById('billingMethod').value == "Visa" || document.getElementById('billingMethod').value == "Mastercard") {
        // We must also check that the appropriate information is included for billing if it's being paid for by credit card
        submittable = (submittable && document.getElementById('cardName').value != '' && document.getElementById('cardNumber').value != '' && document.getElementById('cardExpiryMonth').value != '' && document.getElementById('cardExpiryYear').value != '' && document.getElementById('cardSecurityNumber').value != '');
        
        if (!document.getElementById('billingAddressCheckbox').checked) {
            // If our billing address isn't the same as our shipping address we need to make sure it's filled out
        submittable = (submittable && document.getElementById('billStreetAddress').value != '' && document.getElementById('billCity').value != '' && document.getElementById('billProvince').value != '' && document.getElementById('billCountry').value != '' && document.getElementById('billPostalCode').value != '');
        };
        
    };

    submittable = (submittable && document.getElementById('contactTelephone').value != '' && document.getElementById('contactEmail').value != '');

    document.getElementById('checkoutSubmit').disabled = !submittable;
    
    if (submittable == false) {
        document.getElementById('submitWarning').innerHTML = "<p />Please fill in all of the text boxes on this page.  This information is required to process your order and ensure prompt delivery.";
    } else {
        document.getElementById('submitWarning').innerHTML = " ";
    };
    
    // And finally recalculate the tax totals
    if (document.getElementById('billingMethod').value == "money order" || document.getElementById('billingMethod').value == "cheque" || document.getElementById('billingAddressCheckbox').checked) {
        updateOrderConfirmation('combinedTable', document.getElementById('shipProvince').value, document.getElementById('shipCountry').value);
    } else {
        updateOrderConfirmation('combinedTable', document.getElementById('billProvince').value, document.getElementById('billCountry').value);
    };
}

function selectPaymentType(type) {
    // Figure out which billOrder section needs to be shown
    if (type == "Mastercard" || type == "Visa") {
        var request = newGetAJAXRequestWithURL('/checkout/creditCard.html');
        request.onreadystatechange = showBillingDetailsForm;
        request.send('');
    };
    if (type == "cheque" || type == "money order") {
        var request = newGetAJAXRequestWithURL('/checkout/chequeOrMoneyOrder.html');
        request.onreadystatechange = showBillingDetailsForm;
        request.send('');
    };
}

function showBillingDetailsForm() {
    if (request.readyState == 4) {
        if (request.status == 200) {
            // No error
            var response = request.responseText;
            document.getElementById('billOrder').innerHTML = response;
            toggleBillingAddressEdit();
        } else {
            alert("There was a problem retrieving the data:\n" +
                request.statusText);
        }
    };
}

function selectCreditCardExpiryDateMonth(sender) {
    if (sender.value == "MM") {
        sender.value = "";
        sender.style.color = "#000000";
    };
}

function deselectCreditCardExpiryDateMonth(sender) {
    if (sender.value == "") {
        sender.value = "MM";
        sender.style.color = "#999999";
    } else {
        if (parseInt(sender.value) > 12 || parseInt(sender.value) < 1) {
            var positionX = findPosX(sender);
            var positionY = findPosY(sender);
            document.getElementById("notification").style.opacity = 0;
            setTimeout("raiseNotificationOpacity('0', 0.08, '10')", 100);
            document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
            document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
            document.getElementById("notification").innerHTML = "<p />The expiry month of your credit card should be between 1 and 12.";
            //sender.select(); // We're not holding them at the cc check, so this is for consistency
            setTimeout("lowerNotificationOpacity('1', 0.08, '10')", 2000);
        };
    };
}

function validateCreditCardNumber(ccNumber, sender) {
    // Validates a Visa or Mastercard number using the Mod10 approach
    // Will work for some other brands, but don't count on it
    // Only 16 or 13 digit numbers are valid
    ccNumber = ccNumber.replace(/ /g, "");
    ccNumber = ccNumber.replace(/-/g, "");
    var originalNumberArray = ccNumber.split("");
    var counter = originalNumberArray.length - 1;
    var checksum = 0;
    while (counter >= 0) {
        checksum += parseInt(originalNumberArray[counter]);
        counter -= 2;
    };
    counter = originalNumberArray.length - 2;
    var doubledString = "";
    while (counter >= 0) {
        var doubledNumber = parseInt(originalNumberArray[counter]) * 2;
        doubledString += doubledNumber.toString();
        counter -=2;
    };
    var doubledNumbersArray = doubledString.split("");
    counter = 0;
    while (counter < doubledNumbersArray.length) {
        checksum += parseInt(doubledNumbersArray[counter]);
        counter++;
    };
    if ((checksum%10 == 0 && (originalNumberArray.length == 16 || originalNumberArray.length == 13)) || originalNumberArray.length == 0) {
        // valid
    } else {
        var positionX = findPosX(sender);
        var positionY = findPosY(sender);
        document.getElementById("notification").style.opacity = 0;
        setTimeout("raiseNotificationOpacity('0', 0.08, '10')", 100);
        document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
        document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
        document.getElementById("notification").innerHTML = "<p />Double check your card!  This credit card number doesn't look quite right.";
        setTimeout("lowerNotificationOpacity('1', 0.08, '10')", 3000);
    };
}

function validateCreditCardSecurityNumber(number, sender) {
    // Validates a Visa or Mastercard number using the Mod10 approach
    // Will work for some other brands, but don't count on it
    // Only 16 or 13 digit numbers are valid
    if (number.length == 0 || number.length == 3) {
        // valid
    } else {
        var positionX = findPosX(sender);
        var positionY = findPosY(sender);
        document.getElementById("notification").style.opacity = 0;
        setTimeout("raiseNotificationOpacity('0', 0.08, '10')", 100);
        document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
        document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
        document.getElementById("notification").innerHTML = "<p />This number should be three digits";
        setTimeout("lowerNotificationOpacity('1', 0.08, '10')", 3000);
    };
}

function selectCreditCardExpiryDateYear(sender) {
    if (sender.value == "YY") {
        sender.value = "";
        sender.style.color = "#000000";
    };
}

function deselectCreditCardExpiryDateYear(sender) {
    if (sender.value == "") {
        sender.value = "YY";
        sender.style.color = "#999999";
    };
}

function showSecurityNumberHelp(sender) {
    var positionX = findPosX(sender);
    var positionY = findPosY(sender);
    document.getElementById("notification").style.opacity = 0;
    setTimeout("raiseNotificationOpacity('0', 0.08, '10')", 100);
    document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
    document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
    document.getElementById("notification").innerHTML = "<p />This is a three digit number printed on the back of your credit card to the right of your card number.";
    setTimeout("lowerNotificationOpacity('1', 0.08, '10')", 3000);
}

function validateTelephoneNumber(number, sender) {
    // Validates telephone number for Canada or the US
    number = number.replace(/ /g, "");
    number = number.replace(/-/g, "");
    number = number.replace(/\(/g, "");
    number = number.replace(/\)/g, "");
    number = number.replace(/\./g, "");
    number = number.replace(/\+/g, "");
    // Filter out all the common obfuscating characters
        
    if (number.length == 10 && number[0] != "1") { // patern match goes here
        // valid
    } else if (number.length == 11 && number[0] == "1") {
        // valid
    } else if (number.length == 0) {
        // valid
    } else {
        var positionX = findPosX(sender);
        var positionY = findPosY(sender);
        document.getElementById("notification").style.opacity = 0;
        setTimeout("raiseNotificationOpacity('0', 0.08, '10')", 100);
        document.getElementById("notification").style.left = (positionX-75) + "px"; // not a magic number.  notification div is 150 px wide
        document.getElementById("notification").style.top = (positionY-100) + "px"; // not a magic number.  notification div is 75 px tall
        document.getElementById("notification").innerHTML = "<p />Your phone number doesn't look quite right.  Are you sure you've typed it correctly?";
        setTimeout("lowerNotificationOpacity('1', 0.08, '10')", 3000);
    };
}

function updateOrderConfirmation(required, province, country) {
    var url = "/checkout/checkoutValues.php?required=" + required + "&province=" + province + "&country=" + country;
    orderRequest = false;
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			orderRequest = new XMLHttpRequest();
        } catch(e) {
			orderRequest = false;
        }
    } else if(window.ActiveXObject) {
       	try {
        	orderRequest = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		orderRequest = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		orderRequest = false;
        	}
		}
    };
    orderRequest.open("GET", url, true);
    orderRequest.onreadystatechange = processOrderConfirmationUpdate;
    orderRequest.send('');
}

function processOrderConfirmationUpdate() {
    if (orderRequest.readyState == 4) {
        if (orderRequest.status == 200) {
            // No error
            document.getElementById("orderSums").innerHTML = orderRequest.responseText;
        } else {
            alert("There was a problem recieving your order totals from the server.  The amount you see in your browser may not be accurate.");
        }
    };
}

function catalogRequest() {
	window.open("http://www.stressmarq.com/catalog.html","_blank","toolbar=no, location=no, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=401, height=550");
}


// Third party methods - all methods in public domain

// http://blog.firetree.net/2005/07/04/javascript-find-position/
function findPosX(obj) { // by Peter-Paul Koch & Alex Tingle
    var curleft = 0;
    if(obj.offsetParent)
        while(1) {
            curleft += obj.offsetLeft;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj) { // by Peter-Paul Koch & Alex Tingle
    var curtop = 0;
    if(obj.offsetParent)
        while(1) {
            curtop += obj.offsetTop;
            if(!obj.offsetParent)
                break;
            obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}