﻿

$(document).ready(function() {

    $("div[class^=treeLevel_]").click(function(e) {
        e.preventDefault();
        number = $(this).attr("class").substr($(this).attr("class").length - 1, $(this).attr("class").length);
        if ($(this).next().hasClass("cachedTreeLevelContainer")) {
            if ($(this).next().css("display") == "none") {
                $(".cachedTreeLevelContainer").slideUp("slow");
            }
            $(this).next().slideToggle("slow");
        } else if ($(this).hasClass("treeLevelSelected_" + number)) {
            window.location = $(this).find("a").attr("href");
        } else {
            window.location = $(this).find("a").attr("href");
        }
    });

});



function CheckQuantity(e) {
    if ((isNaN(String.fromCharCode(e.which)) && e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 13) || e.keyCode == 32) {
        e.preventDefault();
    }
}

// Button Function
(function($) {
    $.fn.intellisellButton = function() {
        if ($(this).find('a').length) {
            $(this).find('a').click(function(e) {
                e.preventDefault();
            });
        }
        if ($(this).find('input').length) {
            $(this).find('input').click(function(e) {
                e.preventDefault();
                $(this).parents('.button:first').click();
            });
        }
        if (!window.formSubmitted) {
            window.formSubmitted = false;
        }
        return this.click(function() {
            if ($(this).find('a').length) {
                var classList = $(this).find('a').attr('class').split(/\s+/);
                var value = $(this).find('a').attr('href');

                function ContainsClass(classValue) {
                    if (classValue != null && $.inArray(classValue, classList) > -1) {
                        return true;
                    } else {
                        return false;
                    }
                }

                if (ContainsClass('modal_close')) {
                    $.modal.close();
                };

                if (ContainsClass('toggle')) {
                    $('#' + value).toggle('slow', function() {
                        if ($('#' + value).find('input[type=\'text\']').length) {
                            $('#' + value).find('input[type=\'text\']').focus();
                        }
                        if ($('#' + value).find('.componentViewInner').length) {
                            $('#' + value).find('.componentViewInner').fadeIn('slow');
                        }
                    });
                } else if (ContainsClass('video')) {
                    player.sendEvent('STOP');
                    player.sendEvent('LOAD', value);
                } else if (ContainsClass('report') && ContainsClass('true')) {
                    LoadReportViewer(value, true);
                } else if (ContainsClass('report') && !ContainsClass('true')) {
                    LoadReportViewer(value);
                } else if (ContainsClass('onclick')) {
                    if (value == 'ChangeAccount') {
                        ChangeAccount();
                    }
                    if (value == 'ChangeBranch') {
                        ChangeBranch();
                    }
                } else if (ContainsClass('FancyBox') || ContainsClass('highslide') || $(this).find('a[rel=\'lyteshow\']').length || $(this).find('a[rel=\'lytebox\']').length) {
                    $(this).find('a').click();
                } else {
                    window.location.href = value;
                }
            }
            if ($(this).find('input').length) {
                var submitName = $(this).find('input').attr('name');
                $('.formSubmitButtonID').remove();
                if (submitName.length > 0) {
                    $('<input />', {
                        type: 'hidden',
                        value: 'true',
                        name: submitName,
                        id: submitName
                    }).addClass('formSubmitButtonID').appendTo(this);
                }
                if (window.formSubmitted == false) {
                    window.formSubmitted = true;
                    $(this).parents('form:first').submit();
                }
            }
        });
    };
})(jQuery);

/* Atrribute Filter Function */
(function($) {
    $.fn.attributePanel = function(options) {
        var settings = { 'openGroups': '3' };
        return this.each(function() {
            if (options) { $.extend(settings, options); }
            $('<span />').addClass('-attribute-filter-expanded-icon').prependTo('.-attribute-filter-group:lt(' + settings.openGroups + ') .-attribute-filter-title');
            $('.-attribute-filter-group:gt(' + (settings.openGroups - 1) + ') .-attribute-filter-options').hide();
            $('<span />').addClass('-attribute-filter-expanded-icon collapsed').prependTo('.-attribute-filter-group:gt(' + (settings.openGroups - 1) + ') .-attribute-filter-title');

            $('.-attribute-filter-title').click(function() {
                $(this).next().slideToggle();
                $(this).find('.-attribute-filter-expanded-icon').toggleClass('collapsed');
            });
        });
    };
})(jQuery);

/* GUI Functions */

$(document).ready(function() {
    $("div[id^='componentView_']").each(function() {
        var uid = $(this).attr("id");
        uid = uid.substring(uid.indexOf("_") + 1, uid.length);
        $(this).append($("#componentViewInner_" + uid));
    });

    $('.button').intellisellButton();

    $("div.webMenu").click(function() {
        if (!$(this).find("a[onclick]").length) {
            $(".webMenuSelected").removeClass("webMenuSelected");
            $(this).addClass("webMenuSelected");
            window.location = $(this).find("a").attr("href");
        }
    });



    $("input[type='text'],input[type='radio'],input[type='password'],select,textarea").focus(function() {
        if ($("label[for='" + this.id + "']:not(.error)").length) {
            $(this).addClass("InputFocus");
        }
        $("label[for='" + this.id + "']:not(.error)").addClass("LabelFocus");
        $("fieldset:has(label[for='" + this.id + "']:parent) legend").addClass("LabelFocus");
    });
    $("input[type='text'],input[type='radio'],input[type='password'],select,textarea").blur(function() {
        if ($("label[for='" + this.id + "']:not(.error)").length) {
            $(this).removeClass("InputFocus");
        }
        $("label[for='" + this.id + "']:not(.error)").removeClass("LabelFocus");
        $("fieldset:has(label[for='" + this.id + "']:parent) legend").removeClass("LabelFocus");
    });
    $("form").submit(function() {
        $(":submit", this).click(function() {
            return false;
        });
    });
});

/* End GUI Functions */

function ChangeAccount() {
    if ($('#customerID').val().length > 0) {
        document.location.href = '/Logon/ChangeAccount/' + $('#customerID').val();
    }
}

function ChangeBranch() {
    if ($('#branches').val().length > 0) {
        document.location.href = '/Logon/ChangeAccount/' + $('#branches').val();
    }
}

function OnCustomerSelected(data) {
    if (data.length > 0) {
        $('#customerID').val(data.toString().split(',')[1]);
    }
}

function ValidateStoreBasket() {
    if ($('#basketReference').val().length > 0) {
        return true;
    }
    else {
        return false;
    }
}


function SendContactUsMessage(obj) {
    if ($(obj) != null && $(obj).attr('value').length > 0) {
        $.post("/Account/SendMessage", { message: $(obj).attr('value') }, function(data) {
        });
        $(obj).attr('value', '');
        hs.close();
    }
}

function ValidateQuantity(obj, basketQuantity,
    economicOrderQuantityAction,
    economicOrderQuantity,
    messages) {
    var adjustedQuantity = parseInt(obj.value);
    var adjustmentAction = 1;
    var adjustedMultiples = [];

    switch (economicOrderQuantityAction) {
        case 2:
            if (this.LessThanMinimumQuantity(adjustedQuantity, economicOrderQuantity, basketQuantity) == true) {
                adjustedQuantity = economicOrderQuantity;
                adjustmentAction = 2;
            }
            break;
        case 3:
            var tempQuantity = this.CheckMultiple(adjustedQuantity, economicOrderQuantity);

            if (tempQuantity != adjustedQuantity) {
                adjustedQuantity = tempQuantity;
                adjustmentAction = 3;
            }
            break;
        default:
            break;
    }

    this.SetAdjustedQuantityAndMessage(obj, adjustedQuantity, adjustmentAction, messages);
}

function SetAdjustedQuantityAndMessage(obj, adjustedQuantity, adjustmentAction, messages) {
    if (adjustmentAction > 1) {
        obj.value = adjustedQuantity;
        if ($(obj).siblings(".pioQuantityToolTip").length == 0) {
            $(obj).parent().find("input[type='text']").after('<img src="/Images/pioQuantityToolTip.png" class="pioQuantityToolTip" alt="" title="' + messages[adjustmentAction - 2] + adjustedQuantity + '.' + '" />');
            SetTooltip($(obj).siblings('img'));
        }
    }
    else {
        $(obj).siblings(".pioQuantityToolTip").remove();
    }
}

function LessThanMinimumQuantity(
    requestedQuantity,
    mimimumQuantity,
    basketQuantity) {
    if (mimimumQuantity > 0 && ((requestedQuantity + basketQuantity) < mimimumQuantity)) {
        return true;
    }
    else {
        return false;
    }
}

function CheckMultiple(requestedQuantity, multiple) {
    var quantity = requestedQuantity;

    if (multiple > 0) {
        quantity = (Math.ceil(requestedQuantity / multiple)) * multiple;
    }

    return quantity;
}

function SetTooltipByID(id) {
    $(document).ready(function() {
        var obj = $("#" + id);
        SetTooltip(obj);
    });
}

function SetTooltip(obj) {
    if (obj != null) {
        $(obj).tooltip(
        {
            track: false,
            showURL: false
        });
    }
}

function LoadReportViewer(id, parentIsUserControl) {
    var s = '../';

    if (parentIsUserControl != undefined && parentIsUserControl == true) {
        s = '../../';
    }
    window.open(s + 'Viewer.aspx?id=' + id, 'viewer',
        'top=5,left=5,width=' + (screen.width - 20) + ',height=' + (screen.height - 100) + ',directories=no,location=no,menubar=no,resizable=no,scrollbars=1,status=yes,toolbar=no');
}

function ShowLineNotesDialog(id) {
    $('#' + id).modal(
    {
        overlayId: 'modalOverlay',
        containerId: 'lineNotesDialogContainer'
    });
}

function CarriageChanged() {
    document.getElementById('checkoutForm').setAttribute('action', '/Basket/CarriageChanged');
    document.checkoutForm.submit();
}

function CreatePlayer(theFile, previewFile, go) {
    var s1 = new SWFObject("/Scripts/mediaplayer.swf", "productDetailMediaPlayer", "0", "0", "8");
    s1.addVariable("width", $("#productDetailMediaPlayerContainer").width());
    s1.addVariable("height", $("#productDetailMediaPlayerContainer").height());
    s1.addParam("allowfullscreen", "true");
    s1.addParam("wmode", "transparent");
    s1.addVariable("file", theFile);
    if (go) { s1.addVariable("autostart", "true"); }
    s1.addVariable("image", previewFile);
    s1.write("productDetailMediaPlayerContainer");
}

function IsTextboxEmpty(textbox) {
    var result = false;
    if (textbox != null) {
        if (textbox.value.length > 0) {
            result = true;
        }
    }

    return result;
}

function SubmitFormFromEnter(event, form) {
    if (event && event.which == 13) {
        form.submit();
    }
    else {
        return true;
    }
}

//function for product details back button
function GoBackFromProductDetails() {
    history.go(-1);
}



function CopyAddress(obj) 
{
    if ($(obj).is(':checked') == true) {

        if ($('#addressDeliveryPart1').length > 0) {       
            $('#addressInvoicePart1').val($('#addressDeliveryPart1').val());
        }
        if ($('#addressDeliveryPart2').length > 0) {
            $('#addressInvoicePart2').val($('#addressDeliveryPart2').val());
        }
        if ($('#addressDeliveryPart3').length > 0) {
            $('#addressInvoicePart3').val($('#addressDeliveryPart3').val());
        }
        if ($('#addressDeliveryPart4').length > 0) {
            $('#addressInvoicePart4').val($('#addressDeliveryPart4').val());
        }
        if ($('#addressDeliveryPart5').length > 0) {
            $('#addressInvoicePart5').val($('#addressDeliveryPart5').val());
        }
        if ($('#addressDeliveryPart6').length > 0) {
            $('#addressInvoicePart6').val($('#addressDeliveryPart6').val());
        }
        if ($('#addressDeliveryPart7').length > 0) {
            $('#addressInvoicePart7').val($('#addressDeliveryPart7').val());
        }  
    
    }
}

function ValidateAmountToPay(value, element, params) {
    var result = false;

    var ticked = $("#Tick_" + params.key + ":checked").length > 0 ? true : false;


    if (value.length > 0 && isNaN(value) == false && value > 0 && value <= params.outstandingAmount) {
        result = true;
        if (ticked == true && value < 0.01) {        
            result = false;        
        }
    }

    return result;
}


function TickAllInvoicePayments(tick) 
{
    if (tick == true) 
    {
        $("input.InvoicePaymentsTick").attr('checked', true);
    }
    else 
    {    
        $("input.InvoicePaymentsTick").removeAttr('checked');

    }

    CalculateInvoicePaymentTotal();
}

function CalculateInvoicePaymentTotal() 
{
    var total = 0;

    $("input.InvoicePaymentsTick:checked").each(function(index) {

        var id = $(this).attr('id').replace("Tick_", "");
        var outstandingAmount = $("#OutstandingAmount_" + id).val();

        var params = { key: id, outstandingAmount: parseFloat(outstandingAmount) };

        if (ValidateAmountToPay($("#AmountToPay_" + id).val(), $("#AmountToPay_" + id), params) == true) {
            total += parseFloat($("#AmountToPay_" + id).val());
        }
    });

    $("#totalSelected").html(total.toFixed(2));

    var surcharge = 0;

    if ($("input:radio[name=cardTypes]:checked") != null) 
    { 
        var cardTypeID = $("input:radio[name=cardTypes]:checked").attr('id');
        var rate = $("#SurchargeRate_" + cardTypeID).val();

        if (rate > 0 && total.toFixed(2) > 0) 
        {
            surcharge = ((total.toFixed(2) / 100) * rate);    
        }
    }
   

    $("#surcharge").html(surcharge.toFixed(2));    
}
