﻿//-------------------------------------------
// JQUERY EVENTS
//-------------------------------------------

var OOSHTML;

function getCheckedValue(radioObj) {
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
        return radioObj.value;
    else
        return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

function setCheckedValue(radioObj, newValue) {
    if (!radioObj)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}


$(document).ready(function() {

    // STOCK NOTIFICATION HANDLER
    $("#stockNotifySubmit").click(function() {

        // save the html for after the request - so we can put it back in and allow
        // allow the user to choose to be notified about another matrix point.

        OOSHTML = document.getElementById('StockNotifyLink').innerHTML;

        if (document.getElementById("_notifyEmail").value != "") {
            $(".errortable").hide();
            var hasError = false;
            var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

            var emailToVal = $("#_notifyEmail").val();
            if (!emailReg.test(emailToVal)) {
                //$("#_notifyEmail").after('<span class="errortable">&nbsp;Invalid email</span>');
                document.getElementById("_notifyEmail").style.backgroundColor = "#ef9999";
                document.getElementById("_notifyEmail").value = "Invalid email"
                hasError = true;
            }

            if (hasError == false) {
                $("#_notifyEmail").hide();
                $("#stockNotifySubmit").hide();
                $("#_notifyEmail").after('<img src="/media/images/elements/ajax-loader.gif" alt="Loading" class="loading" />');

                var url = $("#notifyURL").val();
                var ProductID = $("#ProductID").val();
                if ($("#MatrixID")) {
                    var MatrixID = $("#MatrixID").val();
                    var MatrixColour = $("#Matrix2").val();
                    var MatrixColour = $("#Matrix2 option[value=" + MatrixID + "]").text()
                    if ($("#Matrix1")) {
                        var MatrixSize = $("#Matrix1").val();
                    } else {
                        var MatrixSize = "";
                    }
                } else {
                    var MatrixID = "";
                    var MatrixColour = "";
                    var MatrixSize = "";
                }

                jsDelay(1000);

                $.post(url,
                  { notifyEmail: emailToVal, MatrixID: MatrixID, MatrixColour: MatrixColour, MatrixSize: MatrixSize, ProductID: ProductID },
   	                    function(data) {
   	                        $("#stockNotifySubmit").hide();
   	                        $(".loading").hide();
   	                        $("#StockNotifyLink").hide()
   	                        $("#StockNotifySuccess").show()
   	                    }
                );

            }

        } else {
            document.getElementById("_notifyEmail").style.backgroundColor = "#ef9999";
            document.getElementById("_notifyEmail").value = "Please enter your email"
        }
    });

    $("#_notifyEmail").click(function() {
        if ($(this).val() == "Please enter your email" || $(this).val() == "Invalid email") {
            document.getElementById("_notifyEmail").style.backgroundColor = "#FFF";
            document.getElementById("_notifyEmail").value = ""
        }
    });

});

//----------------------------------------------
// FUNCTIONS
//----------------------------------------------

//Matrix Change Options
function getPageValues(data, index, oldMatrixId, type) {
    //alert(data);
    var bits = data.split("~");

    var MatrixID = bits[0];
    var ProductImage1 = bits[1];
    var ProductImage2 = bits[2];
    var ProductImage3 = bits[3];
    var ThumbPhotoFile1 = bits[4];
    var ThumbPhotoFile2 = bits[5];
    var ThumbPhotoFile3 = bits[6];
    var xlPhotoFile1 = bits[7];
    var xlPhotoFile2 = bits[8];
    var xlPhotoFile3 = bits[9];
    var PriceIncVAT = bits[10];
    var PriceExcVAT = bits[11];
    var WasPriceExcVAT = bits[12];
    var WasPriceIncVAT = bits[13];
    var SaveIncVAT = bits[14];
    var SaveExcVAT = bits[15];
    var strStock = bits[16];
    var qis = bits[17];
    var renderType = bits[18];

    //alert("MatrixID " + MatrixID)

    //alert("MatrixID = " + MatrixID +
    //"\nProductImage1 = " + ProductImage1 +
    //"\nProductImage2 = " + ProductImage2 +
    //"\nProductImage3 = " + ProductImage3 +
    //"\nThumbPhotoFile1 = " + ThumbPhotoFile1 +
    //"\nThumbPhotoFile2 = " + ThumbPhotoFile2 +
    //"\nThumbPhotoFile3 = " + ThumbPhotoFile3 +
    //"\nxlPhotoFile1 = " + xlPhotoFile1 +
    //"\nxlPhotoFile2 = " + xlPhotoFile2 +
    //"\nxlPhotoFile3 = " + xlPhotoFile3 +
    //"\nPriceIncVAT = " + PriceIncVAT +
    //"\nPriceExcVAT = " + PriceExcVAT +
    //"\nWasPriceExcVAT = " + WasPriceExcVAT +
    //"\nWasPriceIncVAT = " + WasPriceIncVAT +
    //"\nSaveIncVAT = " + SaveIncVAT +
    //"\nSaveExcVAT = " + SaveExcVAT +
    //"\nstrStock = " + strStock +
    //"\nqis = " + qis);
    
    var doChanges = true;
    if (oldMatrixId != '') { 
        if (document.getElementById('allowOOSPurchase').value != 'true') {
            if (strStock == "0" || strStock == "Out of stock") {
                //doChanges = false;
            }
            else {
                $("#maxQty").val(qis);
                updateQty(qis);
                $("#qtyHolder").show();
            }
        }
    }
    if (doChanges) {

        $("#MatrixID").val(MatrixID);
        if (ProductImage1 != '') {
            $("#mainPhoto").attr('src', ProductImage1);
            $("#thumbl1").val(ProductImage1);
        }
        if (ProductImage2 != '') { $("#thumbl2").val(ProductImage2); }
        if (ProductImage3 != '') { $("#thumbl3").val(ProductImage3); }
        if (ThumbPhotoFile1 != '') { $("#img1").attr('src', ThumbPhotoFile1); }
        if (ThumbPhotoFile2 != '') { $("#img2").attr('src', ThumbPhotoFile2); }
        if (ThumbPhotoFile3 != '') { $("#img3").attr('src', ThumbPhotoFile3); }
        if (xlPhotoFile1 != '') { $("#thumbxl1").val(xlPhotoFile1); }
        if (xlPhotoFile1 != '') { $("#xlPhoto").attr('href', xlPhotoFile1); }
        if (xlPhotoFile2 != '') { $("#thumbxl2").val(xlPhotoFile2); }
        if (xlPhotoFile3 != '') { $("#thumbxl3").val(xlPhotoFile3); }

        $("#pinc").html(PriceIncVAT);
        $("#pexc").html(PriceExcVAT);
        $("#wpexc").html(WasPriceExcVAT);
        $("#wpinc").html(WasPriceIncVAT);
        $("#sinc").html(SaveIncVAT);
        $("#sexc").html(SaveExcVAT);
        $("#psm").html(strStock);

        //if the item is out of stock hide the add to basket button and show the stock notification form
        if (document.getElementById('allowOOSPurchase').value != 'true') {
            if (strStock == "0" || strStock == "Out of stock") {
                $("#buynowcontainer").hide();
                $("#qtyHolder").hide();
                //if (document.getElementById('allowOOSEmail').value == 'true') {
                    //$("#StockNotifySuccess").hide()
                    //$("#_notifyEmail").show();
                    //$("#stockNotifySubmit").show();
                    //$("#StockNotifyLink").show();
                //}
            } else {
                $("#StockNotifySuccess").hide()
                $("#buynowcontainer").show();
                $("#StockNotifyLink").hide();
                $("#maxQty").val(qis);
                updateQty(qis);
                $("#qtyHolder").show();
            }
        }

        //alert("oldMatrixId " + oldMatrixId
        //+ "\nMatrixID " + MatrixID
        //+ "\nIndex" + index
        //+ "\ntype" + type
        // + "\nrender" + renderType)

        if (oldMatrixId != '') {

            var selectedBorderColor = $("#swatchSelectedBorder").val();
            var bordercolor = $("#swatchBorder").val();

            switch (renderType) {
                case "N": case "CD": case "ID":
                    //'default drop down
                    $("#Matrix" + index).val(MatrixID);
                    break;
                case "R": case "IR": case "CR":
                    //radiobutton
                    //alert(getCheckedValue($('input[name="Matrix' + index + '"]')));
                    setCheckedValue($('input[name="Matrix' + index + '"]'), MatrixID);
                    break;
                case "T": case "CT": case "IT":
                    //text in div
                    $("#Matrix" + index + " > div").css("border-color", bordercolor);
                    $("#Matrix-" + index + "-" + MatrixID).css("border-color", selectedBorderColor);
                    break;
                default:
                    //alert(renderType + ' not found');
                    break;
            }

            $("#MatrixSwatch-" + index + "-" + oldMatrixId).css("border-color", bordercolor);
            $("#MatrixSwatch-" + index + "-" + MatrixID).css("border-color", selectedBorderColor);

        }
        $("#MatrixID").val(MatrixID);
    }
}

function getSelectValues(type, data, index, selectedVal) {
    //alert("type " + type + "\nindex" + index + "\nselectedVal" + selectedVal)

    var splitbits = data.split("¬");
    var MatrixID = splitbits[0];
    var AxisCount = splitbits[1];
    var GroupIndex = splitbits[2];
    var renderTypes = splitbits[3].split("|");
    var optionbits = splitbits[4].split("|");
    var swatchBits = splitbits[5].split("|");
    var selectedBits = splitbits[6].split("|");

    var bitsIndex = 0;
    var currentIndex = index + 1
    var selectedBorderColor = $("#swatchSelectedBorder").val();
    var bordercolor = $("#swatchBorder").val();

    for (var i = index; i < renderTypes.length; i++) {

        if (swatchBits.length > 0) {
            $('#MatrixSwatch' + currentIndex).empty();
            $('#MatrixSwatch' + currentIndex).append(swatchBits[i]);
        }

        if (renderTypes[i] == "N" || renderTypes[i] == "CD" || renderTypes[i] == "ID") {
            $('#Matrix' + currentIndex)[0].options.length = 0;
            $('#Matrix' + currentIndex).append(optionbits[i]);
        }
        if (renderTypes[i] == "R" || renderTypes[i] == "CR" || renderTypes[i] == "IR") {
            $('#Matrix' + currentIndex).empty();
            $('#Matrix' + currentIndex).append(optionbits[i]);
        }
        if (renderTypes[i] == "T" || renderTypes[i] == "CT" || renderTypes[i] == "IT") {
            $('#Matrix' + currentIndex).empty();
            $('#Matrix' + currentIndex).append(optionbits[i]);
        }
        $("#swatchvalue-" + currentIndex).val(selectedBits[i]);
        $("#value-" + currentIndex).val(selectedBits[i]);

        if (parseInt(currentIndex) != parseInt(AxisCount)) {
            
            if ($('input[name="Matrix' + currentIndex + '"]').is('input:radio')) {
                setCheckedValue($('input[name="Matrix' + currentIndex + '"]'), selectedBits[i]);
            }
            else {
                $("#Matrix" + currentIndex + " > div").css("border-color", bordercolor);
                $("#Matrix-" + currentIndex + "-" + selectedBits[i].replace(" ", "-")).css("border-color", selectedBorderColor);
            }
            $("#MatrixSwatch" + currentIndex + " > a").css("border-color", bordercolor);
            $("#MatrixSwatch-" + currentIndex + "-" + selectedBits[i].replace(" ", "-")).css("border-color", selectedBorderColor);
        }
        else {
            if ($('input[name="Matrix' + currentIndex + '"]').is('input:radio')) {
                setCheckedValue($('input[name="Matrix' + currentIndex + '"]'), MatrixID);
            }
            else {
                $("#Matrix" + currentIndex + " > div").css("border-color", bordercolor);
                $("#Matrix-" + currentIndex + "-" + MatrixID).css("border-color", selectedBorderColor);
            }
            $("#MatrixSwatch" + currentIndex + " > a").css("border-color", bordercolor);
            $("#MatrixSwatch-" + currentIndex + "-" + MatrixID).css("border-color", selectedBorderColor);
        }
        currentIndex += 1
    }
    //Change selector visible val for text div and swatch
    if ($('input[name="Matrix' + index + '"]').is('input:radio')) {
        setCheckedValue($('input[name="Matrix' + index + '"]'), selectedVal);
    }
    else {
        $("#Matrix" + index + " > div").css("border-color", bordercolor);
        $("#Matrix-" + index + "-" + selectedVal.replace(" ", "-")).css("border-color", selectedBorderColor);
    }
    $("#MatrixSwatch" + index + " > a").css("border-color", bordercolor);
    $("#MatrixSwatch-" + index + "-" + selectedVal.replace(" ", "-")).css("border-color", selectedBorderColor);
 
    return MatrixID
}

function selectionsChanged(type, index, mdata) {

    //alert("index " + index);

    $('#matrixWaiting').show();

    var url = "/ajax/matrix.asp";
    var productid = $("#id").val();

    var matrixdata=''
    if (mdata != '') {
        matrixdata = mdata;
    }
    else {
        matrixdata = $("#Matrix" + index).val();
    }
    
    var axisCount = $("#AxisCount").val();
    var defaultImage1 = $("#default1").val();
    var defaultImage2 = $("#default2").val();
    var defaultImage3 = $("#default3").val();

    var ProductThumb1 = $("#defaultThumb1").val();
    var ProductThumb2 = $("#defaultThumb2").val();
    var ProductThumb3 = $("#defaultThumb3").val();

    if (parseInt(index) != parseInt(axisCount)) {
        //alert("its change axis");
        //Do Change of DropDowns
        var AxisValue1 = "";
        var AxisValue2 = "";
        var AxisValue3 = "";
        var AxisValue4 = "";

        $("#swatchvalue-" + index).val(matrixdata);
        $("#value-" + index).val(matrixdata);

        if ($("#swatchtype-1").val()) {
            AxisValue1 = $("#swatchvalue-1").val();
        }
        else if ($("#type-1").val()) {
            AxisValue1 = $("#value-1").val();
        }

        if (index >= 2) {
            if ($("#swatchtype-2").val()) {
                AxisValue2 = $("#swatchvalue-2").val();
            }
            else if ($("#type-2").val()) {
                AxisValue2 = $("#value-2").val();
            }
        }

        if (index >= 3) {
            if ($("#swatchtype-3").val()) {
                AxisValue3 = $("#swatchvalue-3").val();
            }
            else if ($("#type-3").val()) {
                AxisValue3 = $("#value-3").val();
            }
        }

        if (index >= 4) {
            if ($("#swatchtype-4").val()) {
                AxisValue4 = $("#swatchvalue-4").val();
            }
            else if ($("#type-4").val()) {
                AxisValue4 = $("#value-4").val();
            }
        }

        //alert(  "index " + index +
                //"\nAxisValue1 " + AxisValue1 +
                //"\nAxisValue2 " + AxisValue2 +
                //"\nAxisValue3 " + AxisValue3 +
                //"\nAxisValue4 " + AxisValue4 )

        $.post(url,
        {
            EventType: 'ChangeAxis',
            ProductID: productid,
            AxisCount: axisCount,
            GroupIndex: index,
            AxisValue : matrixdata,
            AxisValue1: AxisValue1,
            AxisValue2: AxisValue2,
            AxisValue3: AxisValue3,
            AxisValue4: AxisValue4
        },
        function(data) {

            //alert(data);
            matrixdata = getSelectValues(type, data, index, matrixdata);
        
            $.post(url,
            {
                ProductID: productid,
                EventType: 'ChangeLastAxis',
                AxisCount: axisCount,
                GroupIndex: index,
                MatrixID: matrixdata,
                ProductImage1: defaultImage1,
                ProductImage2: defaultImage2,
                ProductImage3: defaultImage3,
                ProductThumb1: ProductThumb1,
                ProductThumb2: ProductThumb2,
                ProductThumb3: ProductThumb3
            },
            function(data) {
                getPageValues(data, index, '', type);
            });
        });
    }
    else {
        //Do Change of Matrix ID, Prices, stock and images
        var oldMatrixId = $("#MatrixID").val();
        //alert("its change Last axes");
        //alert("matrixdata2: " + matrixdata);
        
        $.post(url,
        {
            ProductID: productid,
            EventType: 'ChangeLastAxis',
            AxisCount: axisCount,
            GroupIndex: index,
            MatrixID: matrixdata,
            ProductImage1: defaultImage1,
            ProductImage2: defaultImage2,
            ProductImage3: defaultImage3,
            ProductThumb1: ProductThumb1,
            ProductThumb2: ProductThumb2,
            ProductThumb3: ProductThumb3
        },
        function(data) {
            //alert("matrixdata: " + matrixdata +
            //"\naxisCount: " + axisCount +
            //"\nindex: " + index);
            getPageValues(data, index, oldMatrixId, type);
        });
    
    }
    $('#matrixWaiting').hide();
}

function updateQty(qis) {
    var s = $("#Qty").val();
    if (parseInt(s) > parseInt(qis)) {
        $("#Qty").val(qis);
    }
}

//Images on product page
function mouseOverImage(index) {

    var xlImage;
    var lImage;
  
    switch (index) {
        case 1:
            xlImage = $("#thumbxl1").val();
            lImage = $("#thumbl1").val();
            break;
        case 2:
            xlImage = $("#thumbxl2").val();
            lImage = $("#thumbl2").val();
            break;
        case 3:
            xlImage = $("#thumbxl3").val();
            lImage = $("#thumbl3").val();
            break;
        default:
    }

     document.mainPhoto.src = lImage;
     document.getElementById("xlPhoto").href = xlImage;

 }

