﻿/* Function for changing image */
function imagelinkpairrollover(img_name, img_src, li_name, li_class)
{
   document[img_name].src = img_src;
   document.getElementById(li_name).className = li_class;
}

/* 
Master page:
Check that cookies are enabled. If not show message for user

Basket page:
Basket page related jquery events.
BlockUI, show layers to user.
*/
$(document).ready(function () {

    $("#AllCollectionPoints").click(function (event) {
        $("#allcollectionpointsselection").attr("checked", true);
    });

    $("#allcollectionpointsselection").click(function (event) {

        var thisButton = this;
        var radioButtons = $(".noutopisteet input[type=radio]");

        radioButtons.each(function () {
            if (this != thisButton)
                $(this).removeAttr('checked');
        });
    });

    $("#AllCollectionPoints").change(function (event) {
        var selectedCollectionPoint = this.value;
        __doPostBack("allCollectionPoints", selectedCollectionPoint);
    });

    $('.greenBtn').bind('click', function () {
        return validateCollectionPoints(); 
    });

    $('.txtsmall_trigger').bind('change', function () {
        $("form:first").submit();
    });

    var areCookiesEnabled = areCookiesEnabled();
    if (areCookiesEnabled == false) {
        $('#scriptErrorMessage').html("<div class='error-message'><span>Yliopiston Apteekin verkkopalvelun käyttö edellyttää että evästeet (cookies) ovat sallittuja.</span></div>");
    }

    //Show/Hide product batch droppown from left navigation (Tuotesarja)
    handleProductBatchDropDown();

    //Medicine interaction checkup
    var checkupUrl;

    $('#btnCheckup').click(function () {
        checkupUrl = $(this).attr('checkupUrl');
        setBlock('#layerInteractionCheckup');
    });

    $('#continueToInteractionCheckup').click(function () {
        $(window.location).attr('href', checkupUrl);
    });

    $('#cancelInteractionCheckup').click($.unblockUI);

    //continue to contact information button default href value
    var href = $('#continueToContactInformation').attr("href");

    $('#basketContinue').click(function () {
        //user clicks continue button on basket page, blog ui and show login layer
        var isvalid = validateMultipleCheckBoxes();
        if (isvalid) {
            setBlock('#layerlogin');
        }
    });

    $('#continueWithOutLogin').click(function () {
        //user continues shopping with out login in, show age limit layer
        setBlock('#layerAgeLimit');
    });

    $('#agelimitcheckbox').click(function () {
        //user has clicked age limit checkbox, validate checkbox
        validateCheckBox();
    });

    $('#continueToContactInformation').click(function () {
        //user has clicked "Continue" button on age limit layer, validate checkbox
        validateCheckBox();
    });

    $('#toContactInformation').click(function () {
        //user has authenticated and clicked "Continue" button on basket page, validate checkbox
        var isvalid = validateMultipleCheckBoxes();
        if (isvalid) {
            __doPostBack("toContactInformation", true);
        }
    });
    var lineItemId;
    $('.greyBtn').click(function () {
        lineItemId = $(this).attr('lineitemid');
        setBlock('#layerConfirmDelete');
    });

    $('#continueDelete').click(function (event) {
        __doPostBack("continueDelete", lineItemId);
        event.preventDefault();

        // IE6 bug "Magical HTTP Get Request"
        var mode = document.documentMode || 0;
        var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent) && !mode;

        if (ie6) {
            hideBlock("#layerConfirmDelete");
            location.reload(true);
        }

    });

    //Close link clicks unblock ui
    $('#closeLayer').click($.unblockUI);
    $('#closeAgeLimitLayer').click($.unblockUI);
    $('#cancelDelete').click($.unblockUI);

    function validateCollectionPoints() {

        var isValid = false;

        if ($(".noutopisteet").length > 0) {

            var radioButtons = $(".noutopisteet input[type=radio]");

            radioButtons.each(function () {
                if (this.checked == true) {
                    isValid = true;
                }
            });

            var allSelected = $("#allcollectionpointsselection").attr("checked");

            if (allSelected == true && $("#AllCollectionPoints").attr("selectedIndex") == 0)
                isValid = false;

            if (isValid == false) {
                $("#validityInfo").attr({ style: 'visibility:visible;display:inline-block;' });
            }
            else {
                $("#validityInfo").attr({ style: 'visibility:hidden;display:none;' });
            }

            return isValid;

        } else {
            return true;
        }
    }


    function validateMultipleCheckBoxes() {
        var isValid = true;
        var checkbox = $("#productList input[type=checkbox]"); //get all checkboxes on page

        //more than 1 checkbox on page (1 is agelimit checbox)
        checkbox.each(function () {

            if (this.id != "agelimitcheckbox") {
                var control = $('#' + this.id);
                var controlID = control.attr('validateid');

                if (!control.attr('checked')) {
                    isValid = false;
                    $("#productList span[controltovalidate=" + controlID + "]").attr({ style: 'visibility:visible;display:inline-block;' }); //show error message
                }
                else {
                    $("#productList span[controltovalidate=" + controlID + "]").attr({ style: 'visibility:hidden;display:none;' }); //hide error message
                }
            }

            if (isValid == false) {
                $("#validityInfo").attr({ style: 'visibility:visible;display:inline-block;' });
            }
            else {
                $("#validityInfo").attr({ style: 'visibility:hidden;display:none;' });
            }
        });
        return isValid;
    }

    //validata single checkbox
    function validateCheckBox() {
        if (!$('#agelimitcheckbox').attr('checked')) {
            //agelimit checkbox is not checked, show error message to user and remove href value from link
            $("#agelimitError").show();
            $("#continueToContactInformation").removeAttr('href');
        }
        else {
            //agelimit checkbox is checked, hide error message and add href value to link
            $("#agelimitError").hide();
            $("#continueToContactInformation").attr("href", href);
        }
    }

    //set ui block
    function setBlock(divId) {
        $.blockUI.defaults.css = {
            padding: 0,
            margin: 0,
            width: '30%',
            top: '20%',
            left: '15%',
            cursor: 'pointer'
        };

        $.blockUI.defaults.overlayCSS = {
            backgroundColor: '#FFFFFF',
            opacity: 0.6
        };
        $.blockUI({ message: $(divId) });
    }

    //hide ui block
    function hideBlock(divId) {
        $.unblockUI({ message: $(divId) });
    }

    //Print page
    $('#mainContent div.print a').click(function () {
        window.print();
        return false;
    });


    //cookie validation
    function createCookie(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        }
        else expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function eraseCookie(name) {
        createCookie(name, "", -1);
    }

    function areCookiesEnabled() {
        var r = false;
        createCookie("ya.cookie", "1", 1);
        if (readCookie("ya.cookie") != null) {
            r = true;
            eraseCookie("ya.cookie");
        }
        return r;
    }

    //Shows or hides product bath drop down from left navigation (Tuotesarja)
    function handleProductBatchDropDown() {
        // hides the dropdown by default
        $('#productbatch').hide();

        // shows the dropdown on clicking the link
        $('#productbatchdropdown_link').click(function () {
            $("#productbatch").slideToggle();
            return false;
        });
    }

    //FRONT PAGE IMAGE CAROUSEL
    $(".productCarouselContainer1 img").click(function () {
        //discount product carousel used
        showSelectedProductCarouselArea(this, "productCarouselContainer1", "1");
    });
    $(".productCarouselContainer2 img").click(function () {
        //bundle product carousel used
        showSelectedProductCarouselArea(this, "productCarouselContainer2", "2");
    });
    $(".productCarouselContainer1 span").click(function () {
        //discount product carousel used
        showSelectedProductCarouselArea(this, "productCarouselContainer1", "1");
    });
    $(".productCarouselContainer2 span").click(function () {
        //bundle product carousel used
        showSelectedProductCarouselArea(this, "productCarouselContainer2", "2");
    });

    //show selected product carousel area
    function showSelectedProductCarouselArea(selected, cssClass, carouselType) {
        //set selected thumbnail
        $("." + cssClass + " li").attr("class", "");
        //Add class selected to the first ancestor list item
        var currentParent = $(selected).closest("li");
        currentParent.attr("class", "selected");

        //show corresponding info area
        var product = $(selected).attr("product");
        $(".productArea" + carouselType).hide();
        $("#" + product).show();
    }
}); 
