﻿var EMailCheckRegex = new RegExp('[a-zA-Z0-9_\+-]+(\.[a-zA-Z0-9_\+-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})');

window.onresize = function (event) {
    if (document.body.offsetWidth <= 1150) document.getElementById('contactable').style.display = "none";
    if (document.body.offsetWidth > 1150) document.getElementById('contactable').style.display = "inline";
}

function CenterPager(pagerid) {
    if (pagerid != null) {
        var PagerJQuery = jQuery("#" + pagerid);
        var PagerUlPages = jQuery("#" + pagerid + " .pages");

        var MaxWidthOuter = 0;
        //          var MaxWidth = 0;

        jQuery.each(PagerUlPages.children(), function () {
            MaxWidthOuter = MaxWidthOuter + jQuery(this).outerWidth(true);
            //            MaxWidth =  MaxWidth + jQuery(this).width();
        });

        //          alert("MaxWidth:" + MaxWidth + " MaxWidthOuter: " +MaxWidthOuter);

        PagerUlPages.css('width', MaxWidthOuter);
        PagerUlPages.css('marginLeft', 'auto');
        PagerUlPages.css('marginRight', 'auto');
    }
}
 
function IsEmailCheck(email) {
    var regexpattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+jQuery/;
    return regexpattern.test(email);
}

function ValidateAndAddToCart(iId, iMin, iAmount, elemError, url) {
    var bValid = true;
    var sErrors = "";
    elemError.text("");

    if (iAmount < 0 || iAmount < iMin) {
        bValid = false;
        if (iMin > 1) {
            sErrors += "Minimitilausmäärä on " + iMin;
        }
        else {
            sErrors += "Minimitilausmäärä on 1";
        }
    }

    if (bValid == true) {
        ShowProductOverLay(iId);
        CartAddProduct(iId, iAmount, elemError, url);
    }
    else {
        elemError.text(sErrors);
    }
}

function ShowProductOverLay(productid) {
    var Product = jQuery('#' + productid);
    Product.append('<div class="ProductListOverLay"></div><img class="AjaxLoader" src="/Content/Images/Www/ajax-loader.gif" /><span class="AjaxLoadingText">Lisätään<br />Ostoskoriin</span>');
}

function HideProductOverLay(productId) {
    var Product = jQuery('#' + productId);
    if (Product != null) {
        Product.find(".ProductListOverLay").remove();
        Product.find('.AjaxLoader').remove();
        Product.find('.AjaxLoadingText').remove();
    }
}

function CartAddProduct(id, amount, elemError, url) {
    jQuery.post("/Shop/Cart/CartAddProduct",
        {
            iProductId: id,
            iAmount: amount
        },
        function (data, status, xhr) {
            if (data.Success) {
                ReloadMiniShoppingCartPanel(true);
                HideProductOverLay(id);
            }
            else {
                if (data.ParamsMissing != null && data.ParamsMissing == true) {
                    window.location = url;
                }
                else {
                    elemError.text(data.Errors);
                }
            }
        });
}

function ReloadMiniShoppingCartPanel(bProductAdded) {
    jQuery('#MiniShoppingCartWrapper').load('/Shop/ReloadMiniShoppingCartPartial/?rnd=' + Math.random() * 99999, function () {
        if (bProductAdded == true) {
            jQuery("#MiniShoppingCartProductAddedPopup").fadeIn(500);
            jQuery("#MiniShoppingCartProductAddedPopup").delay(2000);
            jQuery("#MiniShoppingCartProductAddedPopup").fadeOut(1000);

            jQuery("#MarginShoppingCartText").innerHTML = jQuery("#MiniShoppingCartProductCount").innerHTML;
        }
    });
}

function LoginAuthCheck() {
    jQuery("#divUserNotActive").hide();
    jQuery("#divUserLoginFailed").hide();

    jQuery("#LoginControls").hide();
    jQuery("#MiniLoginLoading").show();

    jQuery.post("/Login/LoginCheck",
    {
        username: jQuery("#inputMiniLoginBoxUserName").val(),
        password: jQuery("#inputMiniLoginBoxPassword").val()
    },
    function (data, status, xhr) {
        if (data.Success) {
            ReloadMiniLogin();
        }
        else {
            if (data.NotActivated != null && data.NotActivated == true) {
                jQuery("#divUserNotActive").show();
                jQuery("#divUserLoginFailed").hide();
            }
            else {
                jQuery("#divUserNotActive").hide();
                jQuery("#divUserLoginFailed").show();
            }
            jQuery("#LoginControls").show();
            jQuery("#MiniLoginLoading").hide();
        }
    });
}

function ReloadMiniLogin() {
    jQuery('#MiniLoginWrapper').load('/Login/ReloadLoginPartial/?rnd=' + Math.random() * 99999, function () {
        jQuery("#LoginControls").hide();
        jQuery("#MiniLoginLoading").hide();
        window.location.reload();
    });
}

var _bMiniLoginVisibilityState = false;
function ChangeMiniLoginPopoutVisibility() {
    _bMiniLoginVisibilityState = !_bMiniLoginVisibilityState;
    if (_bMiniLoginVisibilityState == true) {
        jQuery("#MiniLoginPopout").show();
    }
    else {
        jQuery("#MiniLoginPopout").hide();
    }
}



//
// Enroll

function ValidateEnrollForm() {
    jQuery("#EnrollForm").validate(
        {
            rules: {
                inputName: { required: true },
                inputAddress: { required: true },
                inputPostCode: { required: true },
                inputPostOffice: { required: true },
                inputPhone: { required: true },
                inputEmail: { required: true, email: true }
            },
            messages: {
                inputName: { required: "Nimi on pakollinen tieto." },
                inputAddress: { required: "Osoite on pakollinen tieto." },
                inputPostCode: { required: "Postinumero on pakollinen tieto." },
                inputPostOffice: { required: "Postitoimipaikka on pakollinen tieto." },
                inputPhone: { required: "Puhelinnumero on pakollinen tieto." },
                inputEmail: { required: "Sähköpostiosoite on pakollinen tieto.", email: "Sähköpostiosoite ei ole oikeaa muotoa." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendEnrollForm() {
    ValidateEnrollForm();
    var bFormValid = jQuery("#EnrollForm").valid();
    if (bFormValid == true) {
        document.forms["EnrollForm"].submit();
    }
}


//
// Registration

function ValidateRegistrationForm() {
    jQuery("#RegistrationForm").validate(
        {
            rules: {
                inputUserName: { required: true },
                inputPassword: { required: true },
                inputPasswordRepeat: { minlength: 8, equalTo: "#inputPassword" },
                inputFirstName: { required: true, maxlength: 100 },
                inputLastName: { required: true, maxlength: 100 },
                inputCompany: { maxlength: 100 },
                inputEmail: { required: true, email: true },
                inputAddress: { required: true, maxlength: 100 },
                inputPostCode: { required: true, maxlength: 100 },
                inputPostOffice: { required: true, maxlength: 100 },
                inputAcceptTerms: { required: true }
            },
            messages: {
                inputUserName: { required: "Nimimerkki on pakollinen tieto." },
                inputPassword: { required: "Salasana on pakollinen tieto." },
                inputPasswordRepeat: { minlength: "Salasanan täytyy olla vähintään 8 merkkiä pitkä.", equalTo: "Salasanat eivät ole samoja." },
                inputFirstName: { required: "Etunimi on pakollinen tieto.", maxlength: "Liian pitkä etunimi" },
                inputLastName: { required: "Sukunimi on pakollinen tieto.", maxlength: "Liian pitkä sukunimi" },
                inputCompany: { maxlength: "Liian pitkä yritys" },
                inputEmail: { required: "Sähköpostiosoite on pakollinen tieto.", email: "Sähköpostiosoite ei ole oikeaa muotoa." },
                inputAddress: { required: "Katuosoite on pakollinen tieto.", maxlength: "Liian pitkä katuosoite" },
                inputPostCode: { required: "Postinumero on pakollinen tieto.", maxlength: "Liian pitkä postinumero" },
                inputPostOffice: { required: "Postitoimipaikka on pakollinen tieto.", maxlength: "Liian pitkä postitoimipaikka" },
                inputAcceptTerms: { required: "Käyttäjäsopimuksen ehdot täytyy hyväksyä." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendRegistrationForm() {
    ValidateRegistrationForm();
    var bFormValid = jQuery("#RegistrationForm").valid();
    if (bFormValid == true) {
        document.forms["RegistrationForm"].submit();
    }
}



//
// Login Index

function ValidateReactivationForm() {
    jQuery("#ReactivationForm").validate(
        {
            rules:
            {
                inputReactivationEmail: { required: true, email: true }
            },
            messages:
            {
                inputReactivationEmail: { required: "Kirjoita sähköpostiosoitteesi.", email: "Sähköpostiosoite ei ole oikeaa muotoa." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function ValidateLoginForm() {
    jQuery("#LoginForm").validate(
        {
            rules:
            {
                inputLoginUserName: { required: true },
                inputLoginPassword: { required: true }
            },
            messages:
            {
                inputLoginUserName: { required: "Kirjoita käyttäjätunnuksesi" },
                inputLoginPassword: { required: "Kirjoita salasanasi" }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendReactivationForm() {
    ValidateReactivationForm();
    var bFormValid = jQuery("#ReactivationForm").valid();
    if (bFormValid == true) {
        document.forms["ReactivationForm"].submit();
    }
}

function SendLoginForm() {
    ValidateLoginForm();
    var bFormValid = jQuery("#LoginForm").valid();
    if (bFormValid == true) {
        document.forms["LoginForm"].submit();
    }
}


//
// Request login

function ValidateRequestLoginForm() {
    jQuery("#RequestLoginForm").validate(
        {
            rules:
            {
                inputRequestLoginEmail: { required: true, email: true }
            },
            messages:
            {
                inputRequestLoginEmail: { required: "Kirjoita sähköpostiosoitteesi.", email: "Sähköpostiosoite ei ole oikeaa muotoa." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendRequestLoginForm() {
    ValidateRequestLoginForm();
    var bFormValid = jQuery("#RequestLoginForm").valid();
    if (bFormValid == true) {
        document.forms["RequestLoginForm"].submit();
    }
}



//
// SendRecommend

function SendSendRecommendForm() {
    ValidateSendRecommendForm();
    var bFormValid = jQuery("#SendRecommendForm").valid();
    var bCapValid = VerifyCalc();

    if (bFormValid == true && bCapValid == true) {
        document.forms["SendRecommendForm"].submit();
    }
}

function VerifyCalc() {
    if (jQuery("#inputCaptchaVerifyValue").val() == jQuery("#inputCaptchaAnswer").val()) {
        return true;
    }
    else {
        jQuery("#ValidationSummary").append("<li><label class='error'>Varmistuslasku ei ole oikein</label></li>");
        return false;
    }
}

function ValidateSendRecommendForm() {
    jQuery("#SendRecommendForm").validate(
        {
            rules: {
                inputSenderName: { required: true },
                inputMessageHeader: { required: true },
                inputRecipientEmail: { required: true, email: true }
            },
            messages: {
                inputSenderName: { required: "Oma nimesi on pakollinen tieto." },
                inputMessageHeader: { required: "Viestin otsikko on pakollinen tieto." },
                inputRecipientEmail: { required: "Ystäväsi sähköpostiosoite on pakollinen tieto.", email: "Sähköpostiosoite ei ole oikeaa muotoa." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}



//
// Change Password

function ValidateChangePasswordForm() {
    jQuery("#ChangePasswordForm").validate(
        {
            rules: {
                inputOldPassword: { required: true },
                inputNewPassword: { required: true },
                inputNewPasswordRepeat: { required: true, minlength: 8, equalTo: "#inputNewPassword" }
            },
            messages: {
                inputOldPassword: { required: "Vanha salasana puuttuu" },
                inputNewPassword: { required: "Uusi salasana puuttuu" },
                inputNewPasswordRepeat: { required: "Uuden salasanan toisto puuttuu.", minlength: "Salasanan täytyy olla vähintään 8 merkkiä pitkä.", equalTo: "Uusi salasana ja toisto ovat erilaiset." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendChangePasswordForm() {
    ValidateChangePasswordForm();
    var bFormValid = jQuery("#ChangePasswordForm").valid();
    if (bFormValid == true) {
        document.forms["ChangePasswordForm"].submit();
    }
}



//
// Upload image

function ValidateUploadImageForm() {
    jQuery("#UploadImageForm").validate(
        {
            rules: {
                inputFile: { required: true, accept: "jpeg|jpg|gif|png" },
                inputDescription: { maxlength: 725 }
            },
            messages: {
                inputFile: { required: "Kuva puuttuu.", accept: "Tiedosto ei ole sallittua tyyppiä. Sallitut kuvatyypit ovat jpg, gif ja png" },
                inputDescription: { maxlength: "Kuvateksti on liian pitkä." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function ismaxlength(obj) {
    var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length > mlength)
        obj.value = obj.value.substring(0, mlength)
}

function SendUploadImageForm() {
    ValidateUploadImageForm();
    var bFormValid = jQuery("#UploadImageForm").valid();
    if (bFormValid == true) {
        document.forms["UploadImageForm"].submit();
    }
}



//
// Question

function ValidateAnswerForm() {
    jQuery("#QuestionAnswerForm").validate(
        {
            rules: {
                inputAnswerText: { required: true },
                inputUserName: { required: true, maxlength: 100 },
                inputName: { required: true, maxlength: 250 },
                inputAddress: { required: true, maxlength: 250 },
                inputPostCode: { required: true, maxlength: 10 },
                inputPostOffice: { required: true, maxlength: 250 },
                inputPhone: { required: true, maxlength: 250 },
                inputEmail: { required: true, email: true, maxlength: 500 }
            },
            messages: {
                inputAnswerText: { required: "Vastaus on pakollinen tieto." },
                inputUserName: { required: "Nimi tai nimimerkki on pakollinen tieto.", maxlength: "Liian pitkä nimi tai nimimerkki." },
                inputName: { required: "Nimi on pakollinen tieto.", maxlength: "Liian pitkä nimi." },
                inputAddress: { required: "Osoite on pakollinen tieto.", maxlength: "Liian pitkä osoite." },
                inputPostCode: { required: "Postinumero on pakollinen tieto.", maxlength: "Liian pitkä postinumero." },
                inputPostOffice: { required: "Postitoimipaikka on pakollinen tieto.", maxlength: "Liian pitkä postitoimipaikka." },
                inputPhone: { required: "Puhelinnumero on pakollinen tieto.", maxlength: "Liian pitkä puhelinnumero." },
                inputEmail: { required: "Sähköpostiosoite on pakollinen tieto.", email: "Sähköpostiosoite ei ole oikeaa muotoa.", maxlength: "Liian pitkä sähköpostiosoite." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendQuestionAnswerForm() {
    ValidateAnswerForm();
    var bFormValid = jQuery("#QuestionAnswerForm").valid();
    if (bFormValid == true) {
        document.forms["QuestionAnswerForm"].submit();
    }
}



//
// Recommend Breakfast

function ValidateRecommendBreakfastForm() {
    jQuery("#RecommendBreakfastForm").validate(
        {
            rules: {
                inputSenderName: { required: true, maxlength: 250 },
                inputSenderEmail: { email: true }
            },
            messages: {
                inputSenderName: { required: "Nimesi on pakollinen tieto.", maxlength: "Nimesi on liian pitkä." },
                inputSenderEmail: { email: "Lähettäjän sähköpostiosoite ei ole oikeaa muotoa." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function RecommendBreakfastValidateRecipients() {
    var bValid = true;
    if (jQuery("#recipients").children().length < 1) {
        if (jQuery("#inputRecipientEmail").val() == "") {
            bValid = false;
            jQuery("#ValidationSummary").append("<li><label class='error'>Vastaanottajan sähköpostiosoite on pakollinen tieto.</label></li>");
        }
        else if (IsEmailCheck(jQuery("#inputRecipientEmail").val()) == false) {
            bValid = false;
            jQuery("#ValidationSummary").append("<li><label class='error'>Vastaanottajan sähköpostiosoite ei ole oikeaa muotoa.</label></li>");
        }
    }
    return bValid;
}

function SendRecommendBreakfastForm() {
    ValidateRecommendBreakfastForm();
    var bFormValid = jQuery("#RecommendBreakfastForm").valid();
    var bRecipientsValid = RecommendBreakfastValidateRecipients();
    var bCapValid = RecommendBreakfastVerifyCalc();

    if (bFormValid == true && bRecipientsValid == true && bCapValid == true) {
        document.forms["RecommendBreakfastForm"].submit();
    }
}

function RecommendBreakfastVerifyCalc() {
    if (jQuery("#inputCaptchaVerifyValue").val() == jQuery("#inputCaptchaAnswer").val()) {
        return true;
    }
    else {
        jQuery("#ValidationSummary").append("<li><label class='error'>Varmistuslasku ei ole oikein</label></li>");
        return false;
    }
}


//
// Send File

function ValidateSendFileForm() {
    jQuery("#SendFileForm").validate(
        {
            rules: {
                inputMessage: { required: true },
                inputSenderName: { required: true, maxlength: 250 },
                inputSenderEmail: { maxlength: 250, email: true }
            },
            messages: {
                inputMessage: { required: "Kirjoita viesti." },
                inputSenderName: { required: "Kirjoita lähettäjän nimi.", maxlength: "Liian pitkä lähettäjän nimi." },
                inputSenderEmail: { email: "Lähettäjän sähköpostiosoite ei ole oikeaa muotoa." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendFileValidateRecipients() {
    var bValid = true;
    if (jQuery("#recipients").children().length < 1) {
        if (jQuery("#inputRecipientEmail").val() == "") {
            bValid = false;
            jQuery("#ValidationSummary").append("<li><label class='error'>Vastaanottajan sähköpostiosoite on pakollinen tieto.</label></li>");
        }
        else if (IsEmailCheck(jQuery("#inputRecipientEmail").val()) == false) {
            bValid = false;
            jQuery("#ValidationSummary").append("<li><label class='error'>Vastaanottajan sähköpostiosoite ei ole oikeaa muotoa.</label></li>");
        }
    }
    return bValid;
}

function SendFileSendForm() {
    ValidateSendFileForm();
    var bFormValid = jQuery("#SendFileForm").valid();
    var bRecipientsValid = SendFileValidateRecipients();

    if (bFormValid == true && bRecipientsValid == true) {
        document.forms["SendFileForm"].submit();
    }
}


//
// UserAccount

function ValidateUserAccountEditForm() {
    jQuery("#UserAccountEditForm").validate(
        {
            rules: {
                inputFirstName: { required: true },
                inputLastName: { required: true },
                inputPhone: { required: true },
                inputEmail: { required: true, email: true },
                inputAddress: { required: true },
                inputPostCode: { required: true },
                inputPostOffice: { required: true }
            },
            messages: {
                inputFirstName: { required: "Etunimi on pakollinen tieto." },
                inputLastName: { required: "Sukunimi on pakollinen tieto." },
                inputPhone: { required: "Puhelinnumero on pakollinen tieto." },
                inputEmail: { required: "Sähköposti on pakollinen tieto.", email: "Sähköpostiosoite ei ole oikeaa muotoa." },
                inputAddress: { required: "Postiosoite on pakollinen tieto." },
                inputPostCode: { required: "Postinumero on pakollinen tieto." },
                inputPostOffice: { required: "Postitoimipaikka on pakollinen tieto." }
            },
            onsubmit: true,
            onkeyup: false,
            onclick: false,
            onfocusout: false,
            errorContainer: "#ValidationSummaryHeader, #ValidationSummary",
            errorLabelContainer: "#ValidationSummary",
            wrapper: "li"
        });
}

function SendUserAccountEditForm() {
    ValidateUserAccountEditForm();
    var bFormValid = jQuery("#UserAccountEditForm").valid();

    if (bFormValid == true) {
        document.forms["UserAccountEditForm"].submit();
    }
}



//
// Product

function CreateProductImageViewDialog() {
    jQuery("#dlgViewImage").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        width: 'auto',
        height: 'auto',
        title: "Tuotekuvat",
        open: function(event, ui) { ProductImageDialogOnOpen(); },
        buttons: { }
    });
}

function InitProductScrollable() {
    jQuery(".Scrollable").scrollable({
        items: ".Items",
        next: ".Next",
        prev: ".Prev",
        speed: 400,
        circular: false,
        disabledClass: "NextPrevDisabled"
    }).navigator({
        navi: ".Navi"
    });
}

function ShowProductImageDialog(index) {
    arrImagesIndex = index;
    jQuery('#dlgImage').attr("src", function () { return arrImages[arrImagesIndex]; });
    jQuery("#dlgViewImage").dialog("open");
}

function ProductImageDialogOnOpen() {
    var tmp = arrImagesIndex + 1;
    jQuery("#ImageIndexText").text(tmp + "/" + arrImages.length);

    if(arrImagesIndex <= 0) {
        jQuery('#dlgPrev').hide();
    }
    else {
        jQuery('#dlgPrev').show();
    }

    if(arrImagesIndex >= arrImages.length - 1) {
        jQuery('#dlgNext').hide();
    }
    else {
        jQuery('#dlgNext').show();
    }
}

function ValidateProductWithModeAndAddToCart(iId, iMin, iMode) {
    document.getElementById("ValidErrorText").innerHTML = "";
    var bValid = true;
    var sErrors = "";

    var attrAmountsArray = new Array();

    if(iMode == 1) {
        var bOneAmountValid = false;
        var bAnyAmountInvalid = false;
        var iCurrentIndex = 0;
        jQuery("[attrAmountInput='true']").each(function(index, Element) {
            var _id = Element.getAttribute("tag");
            var _amount = parseInt(Element.value);

            if(isNaN(_amount) || _amount < 1 || _amount < iMin) {
                bAnyAmountInvalid = true;
            }
            else {
                bOneAmountValid = true;
                attrAmountsArray[iCurrentIndex] = { id: _id, value: _amount };
                iCurrentIndex += 1;
            }
        });

        if(bOneAmountValid == false) {
            bValid = false;
            if(iMin > 1) {
                sErrors += "Minimitilausmäärä on " + iMin + "<br/>"; 
            }
            else {
                sErrors += "Minimitilausmäärä on 1<br/>";
            }
        }
    }
    else
    {
        var iAmount = jQuery("#inputAmount").val();
        if(iAmount < 0 || iAmount < iMin) {
            bValid = false;
            if(iMin > 1) {
                sErrors += "Minimitilausmäärä on " + iMin + "<br/>"; 
            }
            else {
                sErrors += "Minimitilausmäärä on 1<br/>";
            }
        }
    }

    var attr1;
    var attr2;
    var extraParamsArray = new Array();
        
    jQuery("[extraParam='true']").each(function(index, Element) {
        var _id = Element.getAttribute("tag");
        var _value = Element.value;
        extraParamsArray[index] = { id: _id, value: _value };
    });

    if(iMode == 1) {
        var tmp = jQuery("#ParamPrimarySelect").val();
        if(tmp != "") {
            attr1 = tmp;
        }
        else {
            bValid = false;
            sErrors += "Valitse parametrit<br/>";
        }
    }
    else if(iMode == 2) {
        var tmp1 = jQuery("#ParamPrimarySelect").val();
        var tmp2 = jQuery("#ParamSecondarySelect").val();
        if(tmp1 != "" && tmp2 != "") {
            attr1 = tmp1;
            attr2 = tmp2;
        }
        else {
            bValid = false;
            sErrors += "Valitse parametrit<br/>";
        }
    }

    document.getElementById("ValidErrorText").innerHTML = "";
    if (bValid == true) {

        //Before sending the data, clear the fields.
        jQuery("[attrAmountInput='true']").each(function (index, Element) {
            jQuery(this).val('');
        });

        var jsonExtraParams = JSON.stringify(extraParamsArray);
        var jsonAttrAmounts = JSON.stringify(attrAmountsArray);
        CartAddProductWithParams(iId, iAmount, attr1, attr2, jsonExtraParams, jsonAttrAmounts);


    }
    else {
        document.getElementById("ValidErrorText").innerHTML = sErrors;
    }
}

function CartAddProductWithParams(id, amount, attr1, attr2, extraParams, attrAmounts) {
    jQuery.post("/Shop/Cart/CartAddProduct", jQuery.param(
    {
        iProductId: id,
        iAmount: amount,
        iAttrPrimaryId: attr1,
        iAttrSecondaryId: attr2,
        sExtraParameters: extraParams,
        sAttrAmounts: attrAmounts
    }, true),
    function (data, status, xhr) {
        if (data.Success) {
            ReloadMiniShoppingCartPanel(true);
        }
        else {
            document.getElementById("ValidErrorText").innerHTML = data.Errors;
        }
    });
}

function ParamPrimarySelectChanged(id1, id2) {
    document.getElementById("CurrentPrice").innerHTML = "Hinta: Valitse parametrit";
    jQuery("#ParamSecondarySelect").attr("disabled", "disabled");
    FillSecondaryParamList(null);

    var val1 = jQuery("#ParamPrimarySelect").val();

    if(val1 != "") {
        jQuery.post("/Shop/GetSecondaryParams",
        {
            param1: id1,
            param2: id2,
            param3: val1
        },
        function (data, status, xhr) {
            if (data.Success) { 
                FillSecondaryParamList(data.Attr);
                jQuery("#ParamSecondarySelect").attr("disabled", "");
            }
            else { 
                jQuery("#ParamSecondarySelect").attr("disabled", "disabled");
            }
        });
    }
    else {
        jQuery("#ParamSecondarySelect").attr("disabled", "disabled");
    }
}

function ParamSecondarySelectChanged() {
    document.getElementById("CurrentPrice").innerHTML = "Hinta: Valitse parametrit";

    var val1 = jQuery("#ParamPrimarySelect").val();
    var val2 = jQuery("#ParamSecondarySelect").val();

    if(val1 != "" && val2 != "") {
        jQuery.post("/Shop/GetPriceByParams",
        {
            param1: val1,
            param2: val2
        },
        function (data, status, xhr) {
            if (data.Success) {
                document.getElementById("CurrentPrice").innerHTML = "Hinta: " + data.Price.toFixed(2) + " € / kpl";
            }
            else {
                document.getElementById("CurrentPrice").innerHTML = "Hinta: Parametrit virheelliset";
            }
        });
    }
    else {
        document.getElementById("CurrentPrice").innerHTML = "Hinta: Valitse parametrit";
    }
}

function FillSecondaryParamList(attr) {
    var _select = jQuery("#ParamSecondarySelect");

    _select.empty();
    _select.append("<option value=''>--Valitse--</option>");

    if(attr != null)
    {
        var ii = 0;
        for(ii = 0; ii < attr.length; ii++) {
            
            var _elem = "<option value='" + attr[ii].Id + "'>" + attr[ii].Name + "</option>";
            _select.append(_elem);
        }
    }
}


function RenderCard(SenderName, SenderEmail, Header, Message, pictureSrc) {
    var _card = document.getElementById('viewcardCard');
    var _pic = document.getElementById('viewcardPicture');
    var _header = document.getElementById('viewcardHeader');
    var _message = document.getElementById('viewcardMessage');
    var _senderName = document.getElementById('viewcardSenderName');
    // var _senderEmail = document.getElementById('viewcardSenderEmail');

    _senderName.innerHTML = SenderName;
    //_senderEmail.innerHTML = SenderEmail;
    _pic.src = pictureSrc;
    _header.innerHTML = Header;
    _message.innerHTML = Message.replace(/\n/g, "<br>");
    _card.style.display = 'block';
}

function HideCard() {
    var _card = document.getElementById('viewcardCard');
    _card.style.display = 'none';
}

function CenterScrollableNavi(NaviId) {
    var JQueryNavi = jQuery('#' + NaviId);
    if (JQueryNavi != null) {
        var NaviWidth = 0;
        var NaviChildren = JQueryNavi.children();
        jQuery.each(NaviChildren, function () {
            //alert("W(MARGIN):" + jQuery(this).outerWidth(true) + " W:" + jQuery(this).outerWidth());
            NaviWidth = NaviWidth + jQuery(this).outerWidth(true) + jQuery(this).outerWidth(); //for some reason the outerwidth(true) does not include A:Width!!??, so we need to add outerWidth also.
        });

        JQueryNavi.css('width', NaviWidth);
        JQueryNavi.css('marginLeft', 'auto');
        JQueryNavi.css('marginRight', 'auto');
    }
}

function ShowHideCaruselButtons(id) {
    var ViewContainer = jQuery('#ECardSubGroupView_' + id);
    var ViewContainerCarusel = jQuery('#ECardSubGroupView_' + id + ' div[id^="Carusel_"]');
    var api = ViewContainerCarusel.scrollable();

    var PagesCount = ViewContainerCarusel.find('.ItemPage').length;
    if (PagesCount - 1 > api.getIndex()) {

        //next available
        ViewContainer.find('.Next').attr('class', 'Next');
    }
    else {
        //next not available
        ViewContainer.find('.Next').attr('class', 'Next NextPrevDisabled');
    }

    if (PagesCount >= 1) {

        if (api.getIndex() > 0) {
            //prev ava
            ViewContainer.find('.Prev').attr('class', 'Prev');
        }
        else {
            // prev not ava  
            ViewContainer.find('.Prev').attr('class', 'Prev NextPrevDisabled');
        }
    }
    else {
        //prev not available
        ViewContainer.find('.Prev').attr('class', 'Prev NextPrevDisabled');
    }
}

function CaruselClick(action, id) {

    var ViewContainerCarusel = jQuery('#ECardSubGroupView_' + id + ' div[id^="Carusel_"]');
    var api = ViewContainerCarusel.scrollable();

    if (action == 'next') {
        api.next();

        ShowHideCaruselButtons(id);

    }
    else if (action == 'prev') {
        api.prev();

        ShowHideCaruselButtons(id);
    }
}

function ShowSubGroup(iViewId, RootGroupId) {
    var ViewContainer = jQuery("#ECardSubGroupView_" + iViewId);
    var ViewContainerCarusel = jQuery('#ECardSubGroupView_' + iViewId + ' div[id^="Carusel_"]');
    var ViewContainerCaruselItems = jQuery('#ECardSubGroupView_' + iViewId + ' div[id^="Carusel_"] .Items');
    var ViewContainerCaruselNavi = jQuery('#ECardSubGroupView_' + iViewId + ' .NaviWrapper .Navi');
    var RootContainer = jQuery("#ECardRootGroup_" + RootGroupId);
    var RootContainerSubGroups = jQuery("#ECardRootGroup_" + RootGroupId + " .ECardSubGroupViewItem");
    var ViewContainers = jQuery('div[id^="ECardSubGroupView"]');
    var RootContainers = jQuery('div[id^="ECardRootGroup"]');

    jQuery.each(ViewContainers, function () {
        if (jQuery(this).css('display') != 'none') {

            //hide existing items in view
            var ViewContainerSubGroupViewItemsPrevious = jQuery('#' + jQuery(this).attr('id') + ' div[id^="Carusel_"] .Items .ItemPage .ECardSubGroupViewItem');
            jQuery.each(ViewContainerSubGroupViewItemsPrevious, function () {
                jQuery(this).hide();
            });

            //close existing view
            jQuery(this).slideToggle('fast');

        }
    });

    jQuery.each(RootContainers, function () {
        jQuery(this).attr('class', 'ECardRootGroup');
    });


    RootContainer.attr('class', 'ECardRootGroupSelected');

    ViewContainerCaruselItems.html('');
    ViewContainerCaruselNavi.html('');

    var MaxViewableItemsPerPage = 6;
    var MaxItems = RootContainerSubGroups.length;

    for (page = 0; (page < MaxItems / MaxViewableItemsPerPage) || ((MaxItems % MaxViewableItemsPerPage != 0) && (page <= MaxItems / MaxViewableItemsPerPage)); page++) {

        ViewContainerCaruselItems.append('<div class=\"ItemPage\"></div>');
        var ViewContainerCaruselItemsItemPage = ViewContainerCaruselItems.children().last();

        for (indx = page * MaxViewableItemsPerPage; indx < MaxItems && indx < (page * MaxViewableItemsPerPage) + MaxViewableItemsPerPage; indx++) {


            ViewContainerCaruselItemsItemPage.append(RootContainerSubGroups.clone().get(indx));

        }

    }


    var ViewcontainerCaruselItemsPages = jQuery('#ECardSubGroupView_' + iViewId + ' div[id^="Carusel_"] .Items .ItemPage');
    var NaviWrapper = jQuery('#ECardSubGroupView_' + iViewId + ' .NaviWrapper');
    if (ViewcontainerCaruselItemsPages.length <= 1) {
        NaviWrapper.css('display', 'none');
    }
    else {
        NaviWrapper.css('display', 'block');
    }



    //Move to first index inside the carusel.
    var api = ViewContainerCarusel.scrollable();

    try { api.seekTo(0); }
    catch (error) { }


    ShowHideCaruselButtons(iViewId);

    ViewContainerCarusel.navigator({
        navi: ".Navi"
    });

    CenterScrollableNavi(ViewContainerCaruselNavi.attr('id'));

    ViewContainer.slideToggle('slow');

    var ViewContainerSubGroupViewItems = jQuery('#ECardSubGroupView_' + iViewId + ' div[id^="Carusel_"] .Items .ItemPage .ECardSubGroupViewItem');
    jQuery.each(ViewContainerSubGroupViewItems, function () {
        jQuery(this).show('slow');
    });


}

jQuery("a.DeleteRecipient").live("click", function () {
    jQuery(this).parents("div.recipient:first").remove();
    return false;
});

jQuery("#AddRecipient").live("click", function () {
    var sName = jQuery("#inputRecipientName").val();
    var sEmail = jQuery("#inputRecipientEmail").val();
    var bValid = true;
    jQuery("#ValidationSummary").empty();

    if (sEmail == "") {
        bValid = false;
        jQuery("#ValidationSummary").append("<li><label class='error'>Vastaanottajan sähköpostiosoite on pakollinen tieto.</label></li>");
    }
    else if (IsEmailCheck(sEmail) == false) {
        bValid = false;
        jQuery("#ValidationSummary").append("<li><label class='error'>Vastaanottajan sähköpostiosoite ei ole oikeaa muotoa.</label></li>");
    }

    if (bValid == true) {
        var sNewRecDiv = "<div class='recipient'><input name='inputRecipientListName' type='hidden' value='NAME'/><input name='inputRecipientListEmail' type='hidden' value='EMAIL'/>- EMAIL, NAME <a class='DeleteRecipient' href='#'>(poista)</a></div>";
        sNewRecDiv = sNewRecDiv.replace(/NAME/g, sName);
        sNewRecDiv = sNewRecDiv.replace(/EMAIL/g, sEmail);

        jQuery("#recipients").append(sNewRecDiv);

        jQuery("#inputRecipientName").val("");
        jQuery("#inputRecipientEmail").val("");
    }
});

ContentPagerClick = function (pageclickednumber) {
    if (ArchiveUrlAddon != '') {
        document.location = (root + ArchiveUrlAddon + "/" + _PageUrl + "/" + pageclickednumber);
    }
    else {
        document.location = (root + "/" + _PageUrl + "/" + pageclickednumber);
    }
}

function ValidateThankYouForm() {
    jQuery("#AddForm").validate(
            {
                rules:
            {
                FirstName: { required: true, maxlength: 200 },
                LastName: { required: true, maxlength: 200 },
                Company: { required: false, maxlength: 200 },
                Region: { required: false, maxlength: 200 },
                SenderName: { required: true, maxlength: 200 },
                Text: { required: true, maxlength: 1000 },
                Category: { selectNone: true }
            },
                messages: {
                    FirstName: { required: "Syötä etunimi", maxlength: "Liian pitkä etunimi" },
                    LastName: { required: "Syötä sukunimi", maxlength: "Liian pitkä sukunimi" },
                    Company: { required: "Syötä yritys tai yhteisö", maxlength: "Liian pitkä yritys" },
                    Region: { required: "Syötä paikkakunta", maxlength: "Liian pitkä paikkakunta" },
                    SenderName: { required: "Syötä nimimerkkisi", maxlength: "Liian pitkä nimimerkki" },
                    Text: { required: "Syötä sisältöä", maxlength: "Liian pitkä sisältö" },
                    Category: "Valitse kategoria"
                }
            });
}

function ValidateVarssypankkiForm() {
    jQuery("#AddForm").validate(
                    {
                        rules:
                    {
                        Name: { required: true, maxlength: 200 },
                        Text: { required: true, maxlength: 1000 },
                        Category: { selectNone: true }
                    },
                        messages: {
                            Name: { required: "Syötä nimesi", maxlength: "Liian pitkä nimi" },
                            Text: { required: "Syötä sisältöä", maxlength: "Liian pitkä sisältö" },
                            Category: "Valitse kategoria"
                        }
                    });
}

function ShowModalAdd() {
    jQuery("#ModalDivAdd").dialog("open");
}

function CreateModalByMode() {
    switch (ModalMode) {
        case 0:
        case '0':
            {
                //Do nothing!
            }
            break;
        case 1:
        case '1':
            {
                jQuery("#ModalDivAdd").dialog({
                    autoOpen: false, width: 580, height: 600, modal: true, title: 'Lähetä oma kiitoksesi',
                    buttons: {
                        "Lisää": function () {
                            ValidateThankYouForm();

                            var formIsValid = jQuery("#AddForm").valid();
                            if (formIsValid == true) {
                                document.getElementById('hidSendForm').click();
                            }
                        }
                        ,
                        "Peruuta": function () {
                            jQuery(this).dialog("close");
                        }
                    }
                });
            }
            break;
        case 2:
        case '2':
            {
                jQuery("#ModalDivAdd").dialog({
                    autoOpen: false, width: 580, height: 600, modal: true, title: 'Ehdota sisältöä sivulle',
                    buttons: {
                        "Lisää": function () {
                            ValidateVarssypankkiForm();

                            var formIsValid = jQuery("#AddForm").valid();
                            if (formIsValid == true) {
                                document.getElementById('hidSendForm').click();
                            }
                        }
                        ,
                        "Peruuta": function () {
                            jQuery(this).dialog("close");
                        }
                    }
                });
            }
            break;

    }
}

function CreateModalAdd() {
    CreateModalByMode();
}

function SelectPicture(FileName, PictureId, sender) {
    document.getElementById('ECardSelectedCardLarge').src = FileName;
    document.getElementById('SelectedCard').value = PictureId;
    /*jQueryfind('ECardSelectedCardId').value = PictureId;*/

    for (_i = 0; _i < jQuery(".Selected").length; _i++) {
        jQuery(".Selected")[0].className = "Unselected";
    }

    sender.className = 'Selected';
}

function ScrollToPictureParentItem(index) {
    jQuery(".ItemPage img").load(function () { // select active image collection after the images are loaded, otherwise the scroll wont stop in correct position
        //alert("img loaded");
        jQuery(".Scrollable").scrollable().seekTo(index, _pictureScrollSpeed);
    });
}

function InitScrollable() {
    jQuery(".Scrollable").scrollable({
        items: ".Items",
        next: ".Next",
        prev: ".Prev",
        speed: _pictureScrollSpeed,
        circular: false,
        disabledClass: "NextPrevDisabled"
    }).navigator({
        navi: ".Navi"
    });
}

function ECardCategoryMenu() {
    //shows or hides e card category menu

    //alert(jQuery("#ECardCategoryMenu").css('display'));

    if (jQuery("#ECardCategoryMenu").css('display') == 'block') {
        jQuery("#ECardCategoryMenuHeader").html('&raquo; Näytä kaikki korttikategoriat');
        jQuery("#ECardCategoryMenu").css('display', 'none');
    }
    else {
        jQuery("#ECardCategoryMenuHeader").html('&raquo; Piilota kaikki korttikategoriat');
        jQuery("#ECardCategoryMenu").css('display', 'block');
    }

    //alert(jQuery("#ECardCategoryMenuHeader").css('display'));
}


function HideCardPreview() {
    var _showPreviewButton = document.getElementById('btnPreviewCard');
    var _form = document.getElementById('cardForm');

    _showPreviewButton.value = "Esikatsele";
    _showPreviewButton.onclick = ShowCardPreview;
    HideCard();
    _form.style.display = 'block';


}

function ChangeScheduleMode(sender) {
    var _schedule = document.getElementById('ECardSendSchedule');
    //var _date = document.getElementById('txtScheduleDate');
    if (sender.checked) {
        //_date.disabled = false;
        _schedule.style.display = 'block';
    }
    else {
        //_date.value = "";
        //_date.disabled = true;
        _schedule.style.display = 'none';
    }
}

function SelectCurrentCard() {
    var _picToSelect = document.getElementById(('CardSelect_' + _ECardSelectedCard));
    if (_picToSelect != null) {
        SelectPicture(_ECardSelectedCardPictureFilename, _ECardSelectedCardPictureId, _picToSelect);
        var _itemCollectionIndex = _picToSelect.parentNode.id.split("_")[1];
        ScrollToPictureParentItem(parseInt(_itemCollectionIndex));
    }
}

function AddRecipient() {
    var _regex = new RegExp('[a-zA-Z0-9_\+-]+(\.[a-zA-Z0-9_\+-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})');

    var _mRecipient = _regex.exec(jQuery('#txtRecipientEmail').val());
    var _mSender = _regex.exec(jQuery('#txtSenderEmail').val());

    if (_mRecipient != null) { jQuery('#txtRecipientEmail').val(_mRecipient[0]); };
    if (_mSender != null) { jQuery('#txtSenderEmail').val(_mSender[0]); };
    
    document.getElementById("hidSendFormMode").value = _ECardSendFormMode_AddRecipient;
    document.getElementById("btnSendForm").click();
}

function RenderRecipients() {
    var _olRecList = document.getElementById('olRecipientList');
    var _recCount = parseInt(_recipientCount);
    if (_recCount > 0) {
        document.getElementById("lblNoRecipients").style.display = 'none';
        for (var _i = 0; _i < _recCount; _i++) {
            var _recName = document.getElementById("hidRecipientName[" + _i + "]");
            var _recEmail = document.getElementById("hidRecipientEmail[" + _i + "]");
            _olRecList.innerHTML += "<li id='liRecipient[" + _i + "]'>" + _recEmail.value + ", " + _recName.value + " (<a href=\"JavaScript:RemoveRecipient(" + _i + ")\">Poista</a>)</li>";
        }
    }
}

function RemoveRecipient(index) {
    var _recList = document.getElementById('hidRecipientList');
    var _recName = document.getElementById("hidRecipientName[" + index + "]");
    var _recEmail = document.getElementById("hidRecipientEmail[" + index + "]");
    _recList.removeChild(_recName);
    _recList.removeChild(_recEmail);

    var _olRecList = document.getElementById('olRecipientList');
    _olRecList.removeChild(document.getElementById("liRecipient[" + index + "]"));
    if (_olRecList.firstChild == null)
    { document.getElementById('lblNoRecipients').style.display = 'block'; }

}

function ShowCardPreview() {
    var _showPreviewButton = document.getElementById('btnPreviewCard');
    var _form = document.getElementById('cardForm');
    var _cardTitle = document.getElementById('txtCardTitle').value;
    var _cardMessage = document.getElementById('txtCardMessage').value;
    var _cardPictureUrl = _ECardSelectedCardPictureFilename;
    var _senderName = document.getElementById('txtSenderName').value;
    var _senderEmail = document.getElementById('txtSenderEmail').value;

    _showPreviewButton.value = "Muokkaa";
    _showPreviewButton.onclick = HideCardPreview;
    _form.style.display = 'none';
    RenderCard(_senderName, _senderEmail, _cardTitle, _cardMessage, _cardPictureUrl)
}

function loadPictureListBasedOnSelectedPicture(urlname, pageelementId) {
    if (urlname != "") {
        jQuery("#SelectedPicture").hide();

        jQuery("#PictureGalleryEmpty").hide();
        jQuery("#SelectedPictureLoading").show();

        //alert("show loading hide pics - 2");
        jQuery("#PicturesLoading").show();
        jQuery("#Pictures").hide();


        jQuery("#PictureGalleryEmpty").hide();

        jQuery.post("/Kuvagalleria/GetPictureListBasedOnSelectedPicture/" + urlname + "/" + ('' + pageelementId),
            null,
            function (data, status, xhr) {
                ParseData(-1, data);
            });

    }
}
function loadPictureList(urlname, index) {
    if (urlname != "") {
        if (index == -1) {

            jQuery("#SelectedPicture").hide();

            jQuery("#PictureGalleryEmpty").hide();
            jQuery("#SelectedPictureLoading").show();

            //alert("show loading hide pics - 1");
            jQuery("#PicturesLoading").show();
            jQuery("#Pictures").hide();

            jQuery.post("/Kuvagalleria/GetPictureList/" + urlname,
                null,
                function (data, status, xhr) {
                    ParseData(index, data);
                });

        }
        else {
            //alert("show loading hide pics - 2");
            jQuery("#PicturesLoading").show();
            jQuery("#Pictures").hide();


            jQuery("#PictureGalleryEmpty").hide();


            jQuery.post("/Kuvagalleria/GetPictureList/" + urlname + "/" + index,
                null,
                function (data, status, xhr) {
                    ParseData(index, data);
                });
        }
    }
}

function ParseData(index, data) {
    if (data.Success) {

        iCurrentPage = data.CurrentPage;
        iTotalPages = data.TotalPages;
        iPicturesPerPage = data.PicturesPerPage;
        var sFilesUrl = _GallerFilesUrl;
        var sPageId = _GalleryPageId;

        //          alert("Current Page:" +iCurrentPage);
        //          alert("Total Pages:" +iTotalPages);
        //          alert("Pictures per Page:" +iPicturesPerPage);

        jQuery("#Pictures").html('');

        ImgsToBeLoadedCount = 0;
        ImgsLoadedCount = 0;

        jQuery.each(data.Pictures, function (i, picture) {
            ImgsToBeLoadedCount = ImgsToBeLoadedCount + 1;
            var sOnClick = 'Javascript:loadBigPicture(this.getAttribute(' + '\'alt\'' + '),\'' + sFilesUrl + 'Pages/' + sPageId + '/' + picture.Url + '\',\'' + picture.PageElementId + '\' );';
            var sOnError = 'Javascript:ImgLoadFailed(this);';
            var sOnLoad = 'Javascript:ImgLoaded(this);';
            var imggi = '<img class="Picture" src=\"' + sFilesUrl + 'Pages/' + sPageId + '/' + getFileNameWithoutExtension(picture.Url) + '.thumb.jpg\"' + ' alt=\"' + ParseDescription(picture.Description) + '\"' + 'onerror=\"' + sOnError + '\" onclick=\" ' + sOnClick + '\" onload=\" ' + sOnLoad + '\"  /> ';

            //only load first image to selectedPicture when the page has loaded for the first time.
            if (i == 0 && index == -1) {
                //load first image
                if (PreSelectedPictureUlr != "" && ('' + PreSelectedPicturePageElementId) != "" && ('' + PreSelectedPicturePageId) != "") {
                    loadBigPicture('' + PreSelectedPictureDescription, sFilesUrl + 'Pages/' + ('' + PreSelectedPicturePageId) + '/' + ('' + PreSelectedPictureUlr), ('' + PreSelectedPicturePageElementId));
                }
                else {
                    loadBigPicture(picture.Description + '', sFilesUrl + 'Pages/' + sPageId + '/' + picture.Url + '', picture.PageElementId + '');
                }
            }

            jQuery("#Pictures").append(imggi);

        });

        //clear navigation links
        jQuery("#NavigateLeft").html('');
        jQuery("#NavigateRight").html('');

        //Add link to next page
        if (iCurrentPage < iTotalPages) {
            var sImgUrlNext = "../../Content/Images/Www/PictureScrollerRight.gif";
            var sImgUrlNextHove = "../../Content/Images/Www/PictureScrollerRight_hover.gif";
            jQuery("#NavigateRight").html('<img src=\"' + sImgUrlNext + '\" onclick=\"JavaScript:ChangePage(1);\" />');
        }

        //Add link to previous page
        if (iCurrentPage > 1) {
            var sImgUrlPrev = "../../Content/Images/Www/PictureScrollerLeft.gif";
            var sImgUrlNextHove = "../../Content/Images/Www/PictureScrollerLeft_hover.gif";
            jQuery("#NavigateLeft").html('<img src=\"' + sImgUrlPrev + '\" onclick=\"JavaScript:ChangePage(-1);\"/>');
        }

        loadNavigationIndex();

        jQuery("#SelectedPicture").show();
        jQuery("#SelectedPictureLoading").hide();

        //alert("show pics hide loading - 1");
        jQuery("#PicturesLoading").hide();
        jQuery("#Pictures").show();

        //show picture objects from pictures div with easing
        //             jQuery("#Pictures").children().each(function(index) {
        //                jQuery(this).show(500);
        //             });


    }
    else {
        //alert("show pics hide loading - 2");
        jQuery("#SelectedPictureLoading").hide();
        jQuery("#PictureListLoading").hide();
        jQuery("#PictureGalleryEmpty").show();
    }
}

function ChangePage(indexChange) {
    if ((indexChange == 1 && iCurrentPage < iTotalPages) || (indexChange == -1 && iCurrentPage > 1)) {
        loadPictureList(_GalleryPageUrlName, (iCurrentPage + indexChange));
    }

}


function ChangeCommentsPage(indexChange) {
    if ((indexChange == 1 && iCurrentCommentPage < iTotalCommentPages) || (indexChange == -1 && iCurrentCommentPage > 1)) {
        var sCommentsPageElementId = jQuery("#PageElementId").val();
        if (sCommentsPageElementId != "") {
            LoadComments(sCommentsPageElementId, (iCurrentCommentPage + indexChange));
        }
    }

}


function ParseDescription(description) {
    //      alert("Orig desc" + description);

    var parsedDescription = description.replace(/\"/g, "&quot;");
    parsedDescription = parsedDescription.replace(/\'/, "&rsquo;");
    parsedDescription = parsedDescription.replace(/\'/g, "&rsquo;");

    //      alert("Parsed desc" + parsedDescription);

    return parsedDescription;
}

function BigImgLoadFailed(img) {
    jQuery("#SelectedPictureLoading").hide();
    jQuery("#SelectedPicture").show();
    jQuery("#ImgSelectedPicture").show();
    img.setAttribute('onerror', '');
    img.setAttribute('onclick', '');
    img.alt = "";
    img.src = "../../Content/Images/Www/ImgError.jpg";
}

function BigImgLoadSuccess(img) {
    jQuery("#SelectedPictureLoading").hide();
    jQuery("#SelectedPicture").show();
    jQuery("#ImgSelectedPicture").show();
    img.setAttribute('onerror', '');
        
}

function ImgLoadFailed(img) {
    //alert("img load failed");
    img.setAttribute('onerror', '');
    img.setAttribute('onclick', '');
    img.alt = "";
    img.src = "../../Content/Images/Www/ImgError.jpg";
    //alert("onError:" + img.getAttribute('onerror'));
    //alert("onClick:" + img.getAttribute('onclick'));
    //alert(img.getAttribute('alt'));

    ImgLoaded(img);
}


function ImgLoaded(img) {
    ImgsLoadedCount = ImgsLoadedCount + 1;
    //alert("Loaded: "+ImgsLoadedCount);
    if (ImgsLoadedCount == ImgsToBeLoadedCount) {
        AllImgsLoaded();
    }
}

function AllImgsLoaded() {
    //alert("all done");
    jQuery("#Pictures").children().each(function (index) {
        jQuery(this).show(300);
    });
}

function ShowAddCommentDialog() {
    //alert("ShowAddCommentDialog");
    var sPageElementId = '' + jQuery("#PageElementId").val();
    //alert("sPageElementId: " +sPageElementId);
    if (sPageElementId != "") {
        //alert("creating add dialog");

        //clear fields
        jQuery('#comment').val('');


        //reset the form 
        if (AddPictureCommentFormValidator != null) {
            AddPictureCommentFormValidator.resetForm();
        }

        jQuery("#AddPictureCommentDialog").dialog({
            modal: true,
            autoOpen: false,
            resizable: false,
            width: 570, 
            height: 515,
            title: "Lisää kommentti kuvalle",
            buttons: {
                Lähetä: function () {

                    if (AddPictureCommentFormValidator != null && AddPictureCommentFormValidator.form() == true) {
                        jQuery.post("/Comments/AddComment/PageElement/" + ('' + sPageElementId),
                                        {
                                            name: jQuery('#AddPictureCommentForm #name').html(),
                                            comment: jQuery('#AddPictureCommentForm #comment').val()
                                        },

                                        function (data, status, xhr) {
                                            if (data.Success) {
                                                jQuery("#AddPictureCommentDialog").dialog("close");
                                                LoadComments(sPageElementId, iCurrentCommentPage);
                                            }
                                            else {
                                                jQuery(this).dialog("close");
                                                alert("Kommentin lisäys epäonnistui.");
                                            }
                                        });
                    }
                },
                Peruuta: function () {
                    jQuery(this).dialog("close");
                }
            }
        });

        //alert("opening add dialog");
        jQuery("#AddPictureCommentDialog").dialog("open");
    }
}

function CreatePictureAddCommentValidator() {
AddPictureCommentFormValidator = jQuery("#AddPictureCommentForm").validate(
{
    rules:
{
    name: { required: true, maxlength: 100 },
    comment: { required: true, maxlength: 1000 }

},
    messages: {
        name: { required: "Syötä nimesi.", maxlength: "Liian pitkä nimi." },
        comment: { required: "Syötä kommenttisi.", maxlength: "Liian pitkä kommentti." }
    }
});
}


function CreatePictureCommentsDialog() {
jQuery("#CommentsDialog").dialog({
    modal: true,
    autoOpen: false,
    resizable: false,
    width: 550,
    height: 400,
    title: "Kommentit",
    buttons: {
        //            Seuraava: function () {
        //                jQuery("#Comments").html("next");
        //            },
        //            Edellinen: function() {
        //                    jQuery("#Comments").html("prev");
        //            },
        Sulje: function () {
            jQuery(this).dialog("close");
        }
    }
});
}

function CloseBigPictureModalDialog() {
    jQuery("#BigPictureModalDialog").dialog("close");
}

function ShowBigPictureModalDialog(ImgSrc) {
    jQuery("#BigPictureModalDialog img").attr('src', ImgSrc);

    jQuery("#BigPictureModalDialog").dialog({
        modal: true,
        autoOpen: true,
        resizable: false,
        width: "auto",
        height: "auto",
        title: "Kuva",
        buttons: {
            Sulje: function () {

                jQuery(this).dialog("close");
                jQuery("#BigPictureModalDialog img").attr('src', '');
            }
        }
    });
}

function ShowCommentsDialog() {
    //alert("ShowDialog");
    if (iTotalCommentCount > 0) {
        jQuery("#CommentsDialog").dialog("open");
    }
}

function ParseCommentData(index, data) {
    //alert("parse Comments");
    if (data.Success) {

        iCurrentCommentPage = data.CurrentPage;
        iTotalCommentPages = data.TotalPages;
        iCommentsPerPage = data.CommentsPerPage;
        iTotalCommentCount = data.CommentCount;

        //alert("Current Comm Page:" +iCurrentCommentPage);
        //alert("Total Comm Pages:" +iTotalCommentPages);
        //alert("Comments per Page:" +iCommentsPerPage);
        //alert("Total Comm count:" +iTotalCommentCount);

        //Clear control
        jQuery("#Comments").html('');

        jQuery.each(data.Comments, function (i, comment) {
            var sCommentDiv = '<div class=\"Comment\"><span>' + comment.User + '( ' + formatDateTime(comment.Date) + ' )</span><p>' + comment.Text + '</p>';
            jQuery("#Comments").append(sCommentDiv);
        });

        //clear navigation links
        jQuery("#CommentsNavigateLeft").html('');
        jQuery("#CommentsNavigateRight").html('');

        //Add link to next page
        if (iCurrentCommentPage < iTotalCommentPages) {
            var sImgUrlNext = "../../Content/Images/Www/btnNext.png";
            jQuery("#CommentsNavigateRight").html('<img src=\"' + sImgUrlNext + '\" onclick=\"JavaScript:ChangeCommentsPage(1);\" />');

            //jQuery("#CommentsNavigateRight").html('<a style=\"cursor:pointer;\" onclick=\"JavaScript:ChangeCommentsPage(1);\">Seuraava sivu</a>');
        }

        //Add link to previous page
        if (iCurrentCommentPage > 1) {
            var sImgUrlPrev = "../../Content/Images/Www/btnPrevious.png";
            jQuery("#CommentsNavigateLeft").html('<img src=\"' + sImgUrlPrev + '\" onclick=\"JavaScript:ChangeCommentsPage(-1);\" />');
            //jQuery("#CommentsNavigateLeft").html('<a style=\"cursor:pointer;\" onclick=\"JavaScript:ChangeCommentsPage(-1);\">Edellinen sivu</a>');
        }

        loadCommentsNavigationIndex();


        jQuery("#Comments").show();
        jQuery("#CommentsLoading").hide();
    }
    else {
        //Clear control
        jQuery("#Comments").hide();
        jQuery("#CommentsLoading").hide();
        jQuery("#Comments").html('');
        jQuery("#CommentsNavigateLeft").html('');
        jQuery("#CommentsNavigateRight").html('');
        jQuery("#CommentNavigateIndex").html('');
    }
}

function formatDateTime(value) {
    var dte = eval("new " + value.replace(/\//g, '') + ";");

    var _timeStamp = dte.getDate();

    _timeStamp += ".";

    _timeStamp += dte.getMonth() + 1;

    _timeStamp += ".";

    _timeStamp += dte.getFullYear();

    //        _timeStamp += " ";

    //        _timeStamp += dte.getHours();

    //        _timeStamp += ":";

    //        _timeStamp += dte.getMinutes();

    //    _timeStamp += ":";

    //    _timeStamp +=  dte.getSeconds();

    return _timeStamp;
}

function LoadComments(pId, index) {
    //alert("PId :" + pId);
    //alert("ind :" + index);

    var sCompUrl = "/Comments/GetCommentsJSON/" + ('' + pId)
    //alert("sCompUrl:" + sCompUrl );
    if (index == -1) {
        //alert("post1");
        jQuery.post(sCompUrl,
        null,
        function (data, status, xhr) {
            //alert("Comment parse data 1");
            ParseCommentData(index, data);
            AddShowCommentsLink();
        });
    }
    else {
        //alert("post2");
        jQuery.post(sCompUrl + '/' + index,
        null,
        function (data, status, xhr) {
            //alert("Comment parse data 2");
            ParseCommentData(index, data);
            AddShowCommentsLink();
        });
    }

    jQuery("#Comments").hide();
    jQuery("#CommentsLoading").show();
}

function AddShowCommentsLink() {
    if (iTotalCommentCount >= 0) {
        var sOnClick = 'JavaScript:ShowCommentsDialog();';
        var sOnAddClick = 'JavaScript:ShowAddCommentDialog();';

        if (sUserAuth == 'True' || sUserAuth == 'true') {
            jQuery("#ImgActions").html('<div style=\"float:right;"><a style=\"float:right; cursor:pointer;\" onclick=\"' + sOnClick + '\">&raquo; Kommentit (' + iTotalCommentCount + ') </a> </br> <a style=\"cursor:pointer;\" onclick=\"' + sOnAddClick + '\">&raquo; Lisää kommentti </a></div>');
        }
        else {
            jQuery("#ImgActions").html('<div style=\"float:right;"><a style=\"float:right; cursor:pointer;\" onclick=\"' + sOnClick + '\">&raquo; Kommentit (' + iTotalCommentCount + ') </a> </div>');
        }
    }

}

function loadBigPicture(imgAltText, bigImgSrc, pageElementiId) {
    //alert("load big Picture");
    if (bigImgSrc != "") {
        var sPageElementId = '' + pageElementiId;

        jQuery("#SelectedPicture").hide();
        jQuery("#SelectedPictureLoading").show();

        jQuery("#ImgSelectedPicture").remove(); //Remove existing image.

        jQuery("<img id=\"ImgSelectedPicture\" style=\"display:none;\" src=\"" + bigImgSrc + "\" alt=\"" + imgAltText + "\" onerror=\"Javascript:BigImgLoadFailed(this);\" onload=\"Javascript:BigImgLoadSuccess(this);\" onclick=\"JavaScript:ShowBigPictureModalDialog(jQuery(this).attr('src'));\" />").appendTo("#Image");

        jQuery("#ImgDesc").html('<p>' + imgAltText + '</p>');

        jQuery("#ImgFooter").show();

        //OLD
//                jQuery("#ImgSelectedPicture").attr("src", bigImgSrc);
//                jQuery("#ImgSelectedPicture").attr("alt", imgAltText);

//                jQuery("#ImgDesc").html('<p>' + imgAltText + '</p>');


//                jQuery("#ImgSelectedPicture").show();
//                jQuery("#ImgFooter").show();


        //check that the id was provided
        if (sPageElementId != "") {
            jQuery("#PageElementId").val(sPageElementId);

            //whenever we reload the bic picture reset the comment variables
            iCurrentCommentPage = 0;
            iTotalCommentPages = 0;
            iCommentsPerPage = 0;
            iTotalCommentCount = 0;

            LoadComments(sPageElementId, -1);
        }
        else {
            //alert("pid fail");
        }
    }
    else {
        jQuery("#ImgSelectedPicture").hide();
        jQuery("#ImgFooter").hide();
    }
}

function loadCommentsNavigationIndex() {
    if (iCurrentCommentPage > 0 && (iCurrentCommentPage <= iTotalCommentPages)) {
        var CommentsNavigationIndexShowManualNavigate = 'Javascript:CommentsNavigationIndexShowManualNavigate();';
        jQuery("#CommentNavigateIndex").html('<span style="float:left;">(' + iCurrentCommentPage + ' / ' + iTotalCommentPages + ') </span>' + '<a style="float:left; cursor:pointer; margin-left:5px;" onclick=\"' + CommentsNavigationIndexShowManualNavigate + '\" > Siirry </a>');
    }
}

function CommentsNavigationIndexShowManualNavigate() {
    var CommentsNavigationIndexManualNavigate = 'Javascript:CommentsNavigationIndexManualNavigate();';
    jQuery("#CommentNavigateIndex").html('<span style="float:left;">(</span><input id="ManualNavigateIndex" style="float:left; width:20px;" maxlength="3" type="text" value=\"' + iCurrentCommentPage + '\" name="ManualNavigateIndex"/><span style="float:left;"> / ' + iTotalCommentPages + ') </span><a style="float:left; margin-left:5px; cursor:pointer;" onclick=\"' + CommentsNavigationIndexManualNavigate + '\" > Siirry </a>');
}

function CommentsNavigationIndexManualNavigate() {
    var jQueryUserInput = jQuery("#CommentNavigateIndex #ManualNavigateIndex");
    var UserInputValue = jQueryUserInput.attr('value');
    if (UserInputValue > 0 && UserInputValue <= iTotalCommentPages) {
        var sCommentsPageElementId = jQuery("#PageElementId").val();
        if (sCommentsPageElementId != "") {
            LoadComments(sCommentsPageElementId, UserInputValue);
        }
        else {
            loadCommentsNavigationIndex();
        }
    }
    else {
        loadCommentsNavigationIndex();
    }
}

function getFileNameWithoutExtension(filename) {
    return filename.substr(0, filename.lastIndexOf('.')) || filename;
}

function loadNavigationIndex() {
    if (iCurrentPage > 0 && (iCurrentPage <= iTotalPages)) {
        var NavigationIndexShowManualNavigate = 'Javascript:NavigationIndexShowManualNavigate();';
        jQuery("#NavigateIndex").html('<span style="float:left;">(' + iCurrentPage + ' / ' + iTotalPages + ') </span>' + '<a style="float:left; cursor:pointer; margin-left:5px;" onclick=\"' + NavigationIndexShowManualNavigate + '\" > Siirry </a>');
    }
}

function NavigationIndexShowManualNavigate() {
    var NavigationIndexManualNavigate = 'Javascript:NavigationIndexManualNavigate();';
    jQuery("#NavigateIndex").html('<span style="float:left;">(</span><input id="ManualNavigateIndex" style="float:left; width:20px;" maxlength="3" type="text" value=\"' + iCurrentPage + '\" name="ManualNavigateIndex"/><span style="float:left;"> / ' + iTotalPages + ') </span><a style="float:left; margin-left:5px; cursor:pointer;" onclick=\"' + NavigationIndexManualNavigate + '\" > Siirry </a>');
}

function NavigationIndexManualNavigate() {
    var jQueryUserInput = jQuery("#NavigateIndex #ManualNavigateIndex");
    var UserInputValue = jQueryUserInput.attr('value');
    if (UserInputValue > 0 && UserInputValue <= iTotalPages) {
        loadPictureList(_GalleryPageUrlName, UserInputValue);
    }
    else {
        loadNavigationIndex();
    }
}

function stringDecode(stringToDecode) {

    //alert("org:" +stringToDecode);
    Encoder.EncodeType = "numerical";
    Encoder.EncodeType = "entity";
    var DecodedString = Encoder.htmlDecode(stringToDecode);
    //alert("dec:" +DecodedString);
    return DecodedString;
}

function LoadGalleryPage() {
    if (_GalleryPageUrlName != '') {
        if (('' + PreSelectedPicturePageElementId) != "") {
            loadPictureListBasedOnSelectedPicture(_GalleryPageUrlName, ('' + PreSelectedPicturePageElementId));
        }
        else {
            loadPictureList(_GalleryPageUrlName, -1);
        }

        CreatePictureCommentsDialog();
        CreatePictureAddCommentValidator();
    }
    else {
        jQuery("#SelectedPictureLoading").hide();
        jQuery("#PictureGalleryEmpty").show();
    }
}

function LoadSearchPage() {
    if (_SearchQueryText != '') {
        Encoder.EncodeType = "numerical";
        Encoder.EncodeType = "entity";

        var sQueryText = Encoder.htmlDecode(_SearchQueryText);

        jQuery("#queryText").val(sQueryText);
        Search();
    }
}

function CreateSearchPager() {
    var _CurrentPageNumber = 1;
    var _TotalPages = 1;

    if (_SearchResultsPageNumber != null && _SearchResultsPageNumber != undefined) {
        _CurrentPageNumber = _SearchResultsPageNumber;
    }

    if (_SearchResultsTotalPages != null && _SearchResultsTotalPages != undefined) {
        _TotalPages = _SearchResultsTotalPages;
    }

    jQuery("#PagerSearchResults").pager({ pagenumber: parseInt(_CurrentPageNumber), pagecount: parseInt(_TotalPages), buttonClickCallback: SearchPagerClick });
}


SearchPagerClick = function (pageclickednumber) {
    var sSearchQuery = jQuery("#queryText").val();
    sSearchQuery = sSearchQuery.replace(new RegExp(" ", "g"), ';');

    jQuery("#LoadingSearchResults").show();
    jQuery("#aSearch").hide();
    jQuery("#ContentSearchResults").hide();
    jQuery("#PagerSearchResults").hide();
    jQuery("#ContentSearchNoResults").hide();
    jQuery("#ContentSearchResults").load("/Haku/SearchResults/" + sSearchQuery + "/" + pageclickednumber + "/?rnd=" + Math.random() * 99999, function () {
        jQuery("#LoadingSearchResults").hide(); jQuery("#aSearch").show(); jQuery("#ContentSearchResults").show(); jQuery("#PagerSearchResults").show(); CreateSearchPager();

    });
}

function Search() {
    //alert("Searching...");
    var sSearchQuery = jQuery("#queryText").val();
    sSearchQuery = sSearchQuery.replace(new RegExp(" ", "g"), ';');

    if (sSearchQuery != "" && sSearchQuery.length >= MinQueryLengthForSearch) {
        jQuery("#LoadingSearchResults").show();
        jQuery("#aSearch").hide();
        jQuery("#ContentSearchResults").hide();
        jQuery("#PagerSearchResults").hide();
        jQuery("#ContentSearchNoResults").hide();
        jQuery("#ContentSearchResults").load("/Haku/SearchResults/" + sSearchQuery + "/?rnd=" + Math.random() * 99999, function () {
            jQuery("#LoadingSearchResults").hide(); jQuery("#aSearch").show(); jQuery("#ContentSearchResults").show(); jQuery("#PagerSearchResults").show(); CreateSearchPager();

        });
    }
}

ContentControlsCommentPagerClick = function (pageclickednumber) {
    ContentControls_LoadComments(pageclickednumber);
}

function ContentControls_CreateAddCommentFormValidator() {

    AddCommentFormValidator = jQuery("#AddCommentForm").validate(
    {
        rules:
    {
        name: { required: true, maxlength: 100 },
        comment: { required: true, maxlength: 1000 }

    },
        messages: {
            name: { required: "Syötä nimesi.", maxlength: "Liian pitkä nimi." },
            comment: { required: "Syötä kommenttisi.", maxlength: "Liian pitkä kommentti." }
        }
    });
}


function ContentControls_LoadComments(pagenumber) {
    var sTargetId = _ContentControlsTargetId;
    if (sTargetId != "") {
        jQuery("#CommentsLoading").show();
        jQuery("#Comments").hide();
        jQuery("#NoComments").hide();
        jQuery("#Comments").load("/Comments/GetComments/" + sTargetId + "/" + pagenumber + "/?rnd=" + Math.random() * 99999, function () {
            //alert("Comments Loaded..");
            jQuery("#CommentsLoading").hide();
            if (jQuery("#Comments .Comment").length > 0) {
                jQuery("#Comments").show();
                //alert("Showing comments");
                jQuery("#_CommentPager").pager({ pagenumber: parseInt(_CurrentCommentPageNumber), pagecount: parseInt(_CommentTotalPages), buttonClickCallback: ContentControlsCommentPagerClick });
                CenterPager("_CommentPager");
            }
            else {
                //alert("No comments to show");
                jQuery("#NoComments").show();
            }
        });
    }
}

function ContentControls_CreateCommentDialog() {
    var sTargetId = _ContentControlsTargetId;
    var sTargetType = _ContentControlsTargetType;
    if (sTargetId != "" && sTargetType != "") {
        jQuery("#dlgAddComment").dialog({
            modal: true,
            autoOpen: false,
            resizable: false,
            width: 570, 
            height: 515,
            title: "Lisää kommentti",
            buttons: {
                Lähetä: function () {

                    if (AddCommentFormValidator != null && AddCommentFormValidator.form() == true) {
                        jQuery.post("/Comments/AddComment/" + sTargetType + "/" + ('' + sTargetId),
                            {
                                name: jQuery('#AddCommentForm #name').html(),
                                comment: jQuery('#AddCommentForm #comment').val()
                            },

                            function (data, status, xhr) {
                                if (data.Success) {

                                    jQuery("#dlgAddComment").dialog("close");
                                    ContentControls_LoadComments(_CurrentCommentPageNumber);
                                }
                                else {
                                    jQuery(this).dialog("close");
                                    alert("Kommentin lisäys epäonnistui.");
                                }
                            });
                    }

                },
                Peruuta: function () {
                    jQuery(this).dialog("close");
                }
            }
        });
    }
}

function ContentControls_ShowAddCommentDialog() {

    if (AddCommentFormValidator != null) {
        AddCommentFormValidator.resetForm();
    }
    //clear fields
    jQuery('#comment').val('');

    //reopen the dialog which was created with CreateDialog call.
    jQuery("#dlgAddComment").dialog("open");
}

function CreateRootUrl(value) {
    if (value.indexOf("http://") == 0 || value.indexOf("https://") == 0) {
        return value;
    }
    else {
        if (value.indexOf("/") == 0) {
            value = value.substr(1, value.length - 1);
            return jQuery(location).attr('protocol') + '//' + jQuery(location).attr('host') + '/' + value;
        }
        else {
            return jQuery(location).attr('protocol') + '//' + jQuery(location).attr('host') + '/' + value;
        }
    }

}

function MenuItemLinkClick(menuItemLink, OpenInNewWindow, Url) {


    if (Url != "" && menuItemLink != null) {
        //redirect user to another page, in new window or in the current window

        var MenuItemParent = menuItemLink.parents('.MenuItemChildSelected');
        if (MenuItemParent.length == 0) {
            MenuItemParent = menuItemLink.parents('.MenuItemChild');
        }

        if (MenuItemParent.length == 1) {
            MenuItemParent.attr('onclick', ''); //Clear the onclick event of the menuitem link's parent menuitem so we don't get redirected to menuitem's url.
        }

        if (OpenInNewWindow == 'True') {
            //alert("MLINK New Location in new window:" + CreateRootUrl(Url));
            window.open(CreateRootUrl(Url));
        }
        else {
            //alert("MLINK New Location:" + CreateRootUrl(Url));
            window.location = CreateRootUrl(Url);
        }
    }
}

function MenuItemClick(menuItem) {

    var MenuItemUrl = jQuery(menuItem).find('input[name="Url"]').attr('value');
    var MenuItemOpenInNewWindow = jQuery(menuItem).find('input[name="Onw"]').attr('checked');

    if (MenuItemUrl != "") {
        //redirect user to another page, in new window or in the current window
        if (MenuItemOpenInNewWindow == 'True') {
            //alert("MITEM New Location in new window:" + CreateRootUrl(MenuItemUrl));
            window.open(CreateRootUrl(MenuItemUrl));
        }
        else {
            //alert("MITEM New Location:" + CreateRootUrl(MenuItemUrl));
            window.location = CreateRootUrl(MenuItemUrl);
        }
    }

}

function ShowMenuSubItems(menusubItemsId) {
    var MenuSubItemsContainer = jQuery("#MenuSubItems_" + menusubItemsId);

    if (MenuSubItemsContainer != null) {

        jQuery.each(MenuSubItemsContainer.children(), function () {
            jQuery(this).css('display', 'block');
        });

        MenuSubItemsContainer.show();
    }
}

function HideMenuSubItems(menusubItemsId) {

    var MenuSubItemsContainer = jQuery("#MenuSubItems_" + menusubItemsId);

    if (MenuSubItemsContainer != null) {

        jQuery.each(MenuSubItemsContainer.children(), function () {
            jQuery(this).css('display', 'none');
        });

        MenuSubItemsContainer.hide();

    }
}

function RepositionMenuUnderSelectedMenuItem() {
    var MenuItemsJQuery = jQuery("#MenuItems");
    var SelectedMenuItem = MenuItemsJQuery.find(".MenuItemSelected");

    if (SelectedMenuItem.length == 1) {
        var SelectedMenuItemPos = SelectedMenuItem.position();
        var iMenuItemSelectedX = SelectedMenuItemPos.left;
        var iMenuItemSelectedY = SelectedMenuItemPos.top;
        var iMenuItemSelectedWidth = SelectedMenuItem.outerWidth();
        var iMenuItemSelectedHeight = SelectedMenuItem.outerHeight();

        DrawChildMenu(iMenuItemSelectedX, iMenuItemSelectedY, iMenuItemSelectedWidth, iMenuItemSelectedHeight);
    }
}

function DrawChildMenu(iMenuItemSelectedX, iMenuItemSelectedY, iMenuItemSelectedWidth, iMenuItemSelectedHeight) {
    //Make the content of the MenuChildItems container visible only if it contais something.
    if (jQuery("#MenuChildItems").children().length > 0) {

        var iContainerContentWidth = 0;
        var iContainerContentPositionX = 0;
        var iContainerContentPositionY = 0;
        var iContainerWidth = jQuery("#MenuChildItems").outerWidth(true);
        var MenuChildItemsChildren = jQuery("#MenuChildItems").children()

        var iContainerContentWidthNotOuter = 0;

        //calculate the content width of the MenuChildItems container
        jQuery.each(MenuChildItemsChildren, function () {

            iContainerContentWidth = iContainerContentWidth + jQuery(this).outerWidth(true);
            iContainerContentWidthNotOuter = iContainerContentWidthNotOuter + jQuery(this).width();
        });

        iContainerContentPositionX = iMenuItemSelectedX;

        //Make sure that the content can be drawn to available container area -> container is bigger than the content.
        if ((iContainerContentPositionX + iContainerContentWidth) >= iContainerWidth) {
            //alert("MenuChildItems (CHANGED) start X:" + iContainerContentPositionX + " width:" + iContainerContentWidth + " available width:" + iContainerWidth);
            //iContainerContentPositionX = iContainerWidth - iContainerContentWidth;
            if (iContainerContentPositionX + iMenuItemSelectedWidth - iContainerContentWidth < 0) {
                //MenuChildItems container will be out of bounds.
                //try to center it
                iContainerContentPositionX = (iContainerWidth / 2) - (iContainerContentWidth / 2);
            }
            else {
                iContainerContentPositionX = iContainerContentPositionX + iMenuItemSelectedWidth - iContainerContentWidth;
            }
        }
        else {
            //alert("MenuChildItems start X:" + iContainerContentPositionX + " width:" + iContainerContentWidth + " available width:" + iContainerWidth);
        }


        jQuery.each(MenuChildItemsChildren, function () {

            //set the positon of the menuitemchild object based on the provided container content values
            jQuery(this).css('position', 'absolute');
            jQuery(this).css('top', iContainerContentPositionY);
            jQuery(this).css('left', iContainerContentPositionX);

            iContainerContentPositionX = iContainerContentPositionX + jQuery(this).outerWidth(true);
        });


        //finally make the objects visible
        jQuery.each(MenuChildItemsChildren, function () {
            //The MenuItemChild and MenuItemChildSelected elements must be set to visible HERE ONLY. 
            //This is because the elements will stretch their size based on the container they are in if making them visible when adding elements based on the menu objects.
            //                             if (jQuery(this).attr('class') == "MenuItemChild" || jQuery(this).attr('class') == "MenuItemChildSelected") {
            jQuery(this).show();
            //                             }
        });
    }
}


function CreateConfirmRemoveProductDialog() {
    jQuery("#dlgConfirmRemoveProduct").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        title: "Tuotteen poisto",
        buttons: {
            Kyllä: function () {
                var productId = jQuery("#dlgConfirmRemoveProduct #hidproductId").val();
                if (productId != '') {
                    ConfirmedRemoveShoppingCartViewItem(productId);
                    jQuery(this).dialog("close");
                }
                else {
                    jQuery(this).dialog("close");
                }
            },
            Peruuta: function () {
                jQuery(this).dialog("close");
            }
        }
    });
}

function CreateAddGiftCertificateDialog() {
    jQuery("#dlgAddGiftCertificate").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        title: "Lisää kampanjakoodi",
        buttons: {
            Lisää: function () {
                var UserInputtedValue = jQuery("#dlgAddGiftCertificate #addGiftCertificatecode").val();
                if (UserInputtedValue != '') {
                    AddGiftCertificate(UserInputtedValue);
                }
                else {
                    jQuery("#dlgAddGiftCertificate #addGiftCertificateError").html('<span>Tarkista syöttämäsi arvo.</span>');
                }
            },
            Peruuta: function () {
                jQuery(this).dialog("close");
            }
        }
    });
}


function CreateRemoveGiftCertificateDialog() {
    jQuery("#dlgRemoveGiftCertificate").dialog({
        modal: true,
        autoOpen: false,
        resizable: false,
        title: "Poista kampanjakoodi",
        buttons: {
            Sulje: function () {
                jQuery(this).dialog("close");
            }
        }
    });
}

function ShowConfirmRemoveProductDialog(productid) {

    var HiddenProductIdField = jQuery("#dlgConfirmRemoveProduct #hidproductId");

    if (HiddenProductIdField != null) {

        HiddenProductIdField.val(productid);

        jQuery("#dlgConfirmRemoveProduct").dialog('open');
    }
}


function ShowRemoveGiftCertificateDialog() {

    var DialogGiftCertificates = jQuery("#dlgRemoveGiftCertificate .GiftCodes");
    var ShoppingCartCertificates = jQuery("#ShoppingCartGiftCodes #GiftCodes");
    DialogGiftCertificates.html('');
    var GiftCertificateCount = ShoppingCartCertificates.children().length;

    if (GiftCertificateCount > 0) {
        jQuery.each(ShoppingCartCertificates.children(), function () {
            var ClonedChild = jQuery(this).clone();

            ClonedChild.append('<a onclick="JavaScript:RemoveSelectedGiftCertificate(jQuery(this).parent());">Poista</a>');

            DialogGiftCertificates.append(ClonedChild);
        });

        jQuery("#dlgRemoveGiftCertificate #removeGiftCertificateError").html('');
        jQuery("#dlgRemoveGiftCertificate").dialog('open');
    }
}

function ShowAddGiftCertificateDialog() {

    jQuery("#dlgAddGiftCertificate #addGiftCertificateError").html('');
    jQuery("#dlgAddGiftCertificate .inputvalue").val('Syötä koodi');
    jQuery("#dlgAddGiftCertificate").dialog('open');
}

function ShowLoadingShoppingCart() {
    jQuery("#ShoppingCartViewLoading").show();
    jQuery("#ShoppingCartView").hide();
}

function HideLoadingShoppingCart() {
    jQuery("#ShoppingCartViewLoading").hide();
    jQuery("#ShoppingCartView").show();
}

function LoadShoppingCart() {
    //alert("Load SHOP");

    jQuery("#ShoppingCartView").load("/Shop/GetShoppingCartPartialView/?rnd=" + Math.random() * 99999, function () {
        //alert("SHOP Loaded..");
        ReloadMiniShoppingCartPanel(false);
    });
}
function ToggleUpdateShoppingCartViewItemError(productid) {
    var ProductRow = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems #Product_' + productid);
    if (ProductRow != null) {
        var ActionsColumn = ProductRow.find(".ShoppingCartViewValueActions");
        var AmountColumn = ProductRow.find(".ShoppingCartViewValueAmount");
        var AmountColumnValue = ProductRow.find(".ShoppingCartViewValueAmount span").html();
        var DeleteLink = ActionsColumn.find('#aDelete_' + productid);

        if (DeleteLink.length == 0) {

            var Error = AmountColumn.find('.Error');
            if (Error.length != 0) {
                Error.remove();
            }
            else {
                AmountColumn.append('<span class=\"Error\">*</span>');
            }
        }
    }
}
function ToggleUpdateShoppingCartViewItem(productid) {

    var ProductRow = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems #Product_' + productid);
    if (ProductRow != null) {

        var ShoppingCartError = jQuery('#ShoppingCartErrors');
        ShoppingCartError.html(''); //Clear existing error

        //hide error wrapper
        jQuery('#ShoppingCartErrorsWrapper').hide();

        var ProductRows = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems div[id^="Product_"]');
        jQuery.each(ProductRows, function () {

            //Make sure that no other item is in selected state.
            var ProductId = jQuery(this).attr('id');
            var ProductIdValue = ProductId.substr(ProductId.lastIndexOf('_') + 1, ProductId.length - ProductId.lastIndexOf('_') - 1);
            var ProductActionsColumn = jQuery(this).find(".ShoppingCartViewValueActions");
            var ProductDeleteLink = ProductActionsColumn.find('#aDelete_' + ProductIdValue);
            var ProductAmountColumn = jQuery(this).find(".ShoppingCartViewValueAmount");
            var ProductScriptToggle = "Javascript:ToggleUpdateShoppingCartViewItem('" + ProductIdValue + "')";
            var ProductScriptDelete = "Javascript:RemoveShoppingCartViewItem('" + ProductIdValue + "')";
            if (ProductDeleteLink.length == 0) {
                if (jQuery(this).attr("IsAttachedProduct") == 'False') {
                    //if some item is selected or in "edit" state, revert its state to normal.
                    var ProductAmountColumnOrigValue = ProductAmountColumn.find('#EditOrigValue_' + ProductIdValue).attr('value');
                    ProductAmountColumn.html('<span>' + ProductAmountColumnOrigValue + '</span>');
                    ProductActionsColumn.html('<a id=\"aEdit_' + ProductIdValue + '\" onclick=\"' + ProductScriptToggle + '\">Muokkaa</a><a id=\"aDelete_' + ProductIdValue + '\" onclick=\"' + ProductScriptDelete + '\">Poista</a>');
                }
            }
        });

        //Change state to edit for user selected item.
        var ActionsColumn = ProductRow.find(".ShoppingCartViewValueActions");
        var AmountColumn = ProductRow.find(".ShoppingCartViewValueAmount");
        var AmountColumnValue = ProductRow.find(".ShoppingCartViewValueAmount span").html();
        var DeleteLink = ActionsColumn.find('#aDelete_' + productid);
        var ScriptToggle = "Javascript:ToggleUpdateShoppingCartViewItem('" + productid + "')";
        var ScriptDelete = "Javascript:RemoveShoppingCartViewItem('" + productid + ')';
        var ScriptSave = "Javascript:GetNewShoppingCartItemValueAndUpdate('" + productid + "');";
        var ScriptCancel = "Javascript:LoadShoppingCart();";

        if (DeleteLink.length != 0) {
            //Swap to edit view
            AmountColumn.html('<input id=\"EditOrigValue_' + productid + '\" type=\"hidden\" value=\"' + AmountColumnValue + '\"><input id=\"EditValue_' + productid + '\" type=\"text\" style=\"width:20px;\" maxlength=\"3\" value=\"' + AmountColumnValue + '\">');
            ActionsColumn.html('<a id=\"aSave_' + productid + '\" onclick=\"' + ScriptSave + '\">Tallenna</a><a id=\"aCancel_' + productid + '\" onclick=\"' + ScriptCancel + '\">Peruuta</a>');
        }
        else {
            //Swap back to normal view
            var AmountColumnOrigValue = AmountColumn.find('#EditOrigValue_' + productid).attr('value');
            AmountColumn.html('<span>' + AmountColumnOrigValue + '</span>');
            ActionsColumn.html('<a id=\"aEdit_' + productid + '\" onclick=\"' + ScriptToggle + '\">Muokkaa</a><a id=\"aDelete_' + productid + '\" onclick=\"' + ScriptDelete + '\">Poista</a>');

        }
    }
}

function GetNewShoppingCartItemValueAndUpdate(productid) {
    var ProductRow = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems #Product_' + productid);
    if (ProductRow != null) {
        var NewAmountValue = ProductRow.find('.ShoppingCartViewValueAmount #EditValue_' + productid).attr('value');
        UpdateShoppingCartViewItem(productid, NewAmountValue);
    }
}

function UpdateShoppingCartViewItem(productId, value) {

    ShowProductRowLoading(productId);

    jQuery.post("/Shop/Cart/CartEditProductAmount",
{
    gUniqueId: productId,
    iNewAmount: value
}, function (data, status, xhr) {
    UpdateShoppingCartViewItemResult(productId, value, data);
});
}

function UpdateShoppingCartViewItemResult(productId, newvalue, data) {
    var ProductRow = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems #Product_' + productId);
    if (ProductRow != null) {
        //alert("Update Product found");
        if (data.Success) {
            var OriginalAmountValueField = ProductRow.find('.ShoppingCartViewValueAmount #EditOrigValue_' + productId);
            if (OriginalAmountValueField.length > 0) {
                //alert("Update Product value found");
                OriginalAmountValueField.val(newvalue);
                //alert("Update product new value:" + OriginalAmountValueField.val());
                //ToggleUpdateShoppingCartViewItem(productId);
                LoadShoppingCart();
            }
            else {
                // alert("Update Product value not found");

            }
        }
        else {
            ToggleUpdateShoppingCartViewItemError(productId);
            if (data.Errors.length > 0) {
                var ShoppingCartError = jQuery('#ShoppingCartErrors');
                if (ShoppingCartError != null) {

                    ShoppingCartError.html('<span class=\"Error\">' + data.Errors + '</span>');
                    //show error wrapper
                    jQuery('#ShoppingCartErrorsWrapper').show();
                }
            }
            HideProductRowLoading(productId);

        }
    }
    else {
        //alert("Update Product not found");
    }
}

function RemoveSelectedGiftCertificate(selecteditem) {
    var giftcode = selecteditem.find('.code').val();

    if (giftcode != null) {
        RemoveGiftCertificate(giftcode);
    }
}

function RemoveSelectedGiftCertificateFromRemoveDialog(giftcode) {
    var DialogGiftCertificates = jQuery("#dlgRemoveGiftCertificate .GiftCodes");

    jQuery.each(DialogGiftCertificates.children(), function () {
        var childgiftCode = jQuery(this).find('.code').val();

        if (giftcode == childgiftCode) {
            jQuery(this).remove();
        }
    });

    if (DialogGiftCertificates.children().length == 0) {

        DialogGiftCertificates.append('<span>Ostoskoriin ei ole liitetty yhtään kampanjakoodia.</a>');
    }
}

function ShowProductRowLoading(productId) {
    var ProductRow = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems #Product_' + productId);
    if (ProductRow != null) {

        var ProductRowHeight = ProductRow.height();
        var ProductRowWidth = ProductRow.width();

        ProductRow.append('<div class="EditOverLay"><img class="AjaxLoader" src="/Content/Images/Www/ajax-loader.gif" /><span  class="AjaxLoadingText">Tallennetaan</span></div>');

        var EditOverLay = ProductRow.find(".EditOverLay");
        if (EditOverLay != null) {
            EditOverLay.css('width', ProductRowWidth);
            EditOverLay.css('height', ProductRowHeight);
        }
    }
}

function HideProductRowLoading(productId) {

    var ProductRow = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems #Product_' + productId);
    if (ProductRow != null) {

        var EditOverLay = ProductRow.find(".EditOverLay");
        var AjaxLoader = ProductRow.find(".AjaxLoader");
        var AjaxLoadingText = ProductRow.find(".AjaxLoadingText");

        if (AjaxLoadingText != null) {
            AjaxLoadingText.remove();
        }

        if (AjaxLoader != null) {
            AjaxLoader.remove();
        }

        if (EditOverLay != null) {
            EditOverLay.remove();
        }
    }
}

function RemoveShoppingCartViewItem(productId) {
    ShowConfirmRemoveProductDialog(productId);
}


function ConfirmedRemoveShoppingCartViewItem(productId) {
    ShowProductRowLoading(productId);

    jQuery.post("/Shop/Cart/CartRemoveProduct",
    {
        gUniqueId: productId
    },
        function (data, status, xhr) {
            if (data.Success) {
                RemoveShoppingCartViewItemResult(productId, true);
            }
            else {
                RemoveShoppingCartViewItemResult(productId, false);
                HideProductRowLoading(productId);

            }
        });
}


function AddGiftCertificate(giftcode) {
    jQuery.post("/Shop/Cart/AddGiftCertificate",
    {
        giftcode: giftcode
    },
        function (data, status, xhr) {
            AddGiftCertificateResult(data, giftcode);
        });
}

function AddGiftCertificateResult(data, giftcode) {
    if (data.Success) {
        jQuery("#dlgAddGiftCertificate").dialog('close');
        LoadShoppingCart();

    }
    else {

        if (data.Errors != null) {
            jQuery("#dlgAddGiftCertificate #addGiftCertificateError").html('<span>' + data.Errors + '</span>');
        }
    }
}


function RemoveGiftCertificate(giftcode) {
    jQuery.post("/Shop/Cart/RemoveGiftCertificate",
    {
        giftcode: giftcode
    },
        function (data, status, xhr) {
            RemoveGiftCertificateResult(data, giftcode);
        });
}

function RemoveGiftCertificateResult(data, giftcode) {
    if (data.Success) {
        jQuery("#dlgAddGiftCertificate").dialog('close');
        LoadShoppingCart();
        RemoveSelectedGiftCertificateFromRemoveDialog(giftcode);

    }
    else {

        if (data.Errors != null) {
            jQuery("#dlgAddGiftCertificate #addGiftCertificateError").html('<span>' + data.Errors + '</span>');
            jQuery("#dlgRemoveGiftCertificate #removeGiftCertificateError").html('<span>' + data.Errors + '</span>');
        }
    }
}

function RemoveShoppingCartViewItemResult(productId, bResult) {

    //alert("RemoveProductReuslt:" + bResult);

    var ProductRow = jQuery('#ShoppingCartViewContent #ShoppingCartViewItems #Product_' + productId);
    if (ProductRow != null) {

        if (bResult == true) {
            //ProductRow.hide('slow').remove();
            LoadShoppingCart();
        }
        else {

            alert("Tuotetta ei voitu poistaa.");
        }
    }
    //alert("Remove done");
}

function ClearShoppingCartView() {

    jQuery.post("/Shop/Cart/CartClear",
    {
},
        function (data, status, xhr) {
            if (data.Success) {
                ClearShoppingCartViewResult(true);
            }
            else {
                ClearShoppingCartViewResult(false);
            }
        });
}

function ClearShoppingCartViewResult(bResult) {
    if (bResult == true) {
        LoadShoppingCart();
    }
    else {

    }
}

function PageLoaded() {
    SetContactableVisibility();
    RepositionMenuUnderSelectedMenuItem();
}

function SetContactableVisibility() {
    if (document.body.offsetWidth > 1150) { jQuery(function () { jQuery('#contactable').contactable({}); }); }
}

function SendECardForm() {
    var _regex = new RegExp('[a-zA-Z0-9_\+-]+(\.[a-zA-Z0-9_\+-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.([a-zA-Z]{2,4})');

    var _mRecipient = _regex.exec(jQuery('#txtRecipientEmail').val());
    var _mSender = _regex.exec(jQuery('#txtSenderEmail').val());

    if (_mRecipient != null) { jQuery('#txtRecipientEmail').val(_mRecipient[0]); };
    if (_mSender != null) { jQuery('#txtSenderEmail').val(_mSender[0]); };

    jQuery('#txtCardMessage').val(jQuery('#txtCardMessage').val().replace(new RegExp("<", "g"), '&lt;'));
    jQuery('#txtCardMessage').val(jQuery('#txtCardMessage').val().replace(new RegExp(">", "g"), '&gt;'));

    jQuery('#txtCardTitle').val(jQuery('#txtCardTitle').val().replace(new RegExp("<", "g"), '&lt;'));
    jQuery('#txtCardTitle').val(jQuery('#txtCardTitle').val().replace(new RegExp(">", "g"), '&gt;'));

    document.forms["formSend"].submit();
}

function ParseEMail(object) {
    var _m = EMailCheckRegex.exec(jQuery('#' + object.id).val());
    if (_m != null) { jQuery('#' + object.id).val(_m[0]); }
}
