﻿function GetDefaultImageUrl(productImages, imageType) {

    var imageUrl = "images/public/prod1.gif";
    var defImgUrl = '';
    if (productImages != null && productImages.length > 0) {
        for (var i = 0; i < productImages.length; i++) {

            if (productImages[i].DefaultImage == true) {
                defImgUrl = productImages[i].ImageURL;
            }
        }
        if (defImgUrl == '') {
            defImgUrl = productImages[0].ImageURL;
        }

        var str = defImgUrl.split("/");

        switch (imageType) {
            case "default":
                imageUrl = productImages[i].ImageURL;
                break;
            case "productDetails":
                imageUrl = str[0] + "/" + str[1] + "/" + str[2] + "/thumbs/first" + str[3] + ".ashx";
                break;
            case "productList":
                imageUrl = str[0] + "/" + str[1] + "/" + str[2] + "/thumbs/second" + str[3] + ".ashx";
                break;
            case "new":
                imageUrl = str[0] + "/" + str[1] + "/" + str[2] + "/thumbs/third" + str[3] + ".ashx";
                break;
            case "productDetailsThumb":
                imageUrl = str[0] + "/" + str[1] + "/" + str[2] + "/thumbs/fourth" + str[3] + ".ashx";
                break;
            default:
                imageUrl = "images/public/prod1.gif.ashx";
        }
    }
    return imageUrl;
}

function SearchProducts(id, name, manufacturerID, categoryID, description, price, discountPrice, onDiscount, xxlDiscount, newProduct, dimension, lastUpdateDate, color, materials, pageNumber, pageSize, sortParameter, sortAscending) {
    var collection;
    var args = "{ id: '" + id +
                          "' ,name: '" + name +
                          "' ,manufacturerID: '" + manufacturerID +
                          "' ,categoryID: '" + categoryID +
                          "' ,description: '" + description +
                          "' ,price: '" + price +
                          "' ,discountPrice: '" + discountPrice +
                          "' ,onDiscount: '" + onDiscount +
                          "' ,xxlDiscount: '" + xxlDiscount +
                          "' ,newProduct: '" + newProduct +
                          "' ,dimension: '" + dimension +
                          "' ,lastUpdateDate: '" + lastUpdateDate +
                          "' ,color: '" + color +
                          "' ,materials: '" + materials +
                          "' ,pageNumber: '" + pageNumber +
                          "' ,pageSize: '" + pageSize +
                          "' ,sortParameter: '" + sortParameter +
                          "' ,sortAscending: '" + sortAscending +
            "'}";
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Service/AjaxService.asmx/SearchProducts",
        data: args,
        dataType: "json",
        success: function (data) {
            collection = data.d;
        },
        error: function (a1) {
            alert(a1.responseText);
        }
    });
    return collection;
}

function GetProductList(page, sortParameter, sortAscending) {
    var productsCollection = SearchProducts("", "", "", productCategoryID, "", "", "", "", "","", "", "", "", "", page, 12, sortParameter, sortAscending);

    switch (currentCulture.toLowerCase()) {
        case "mk-mk":
            $("#recordInfo").text("Пронајдени се [ " + productsCollection.RecordCount + " ] производи");
            break;
        case "sq-al":
            $("#recordInfo").text("Janë gjetur [ " + productsCollection.RecordCount + " ] produkteve");
            break;
    }

    if (page == 1) {
        RenderPaging(productsCollection.RecordCount, productsCollection.PageSize, page, sortParameter, sortAscending);
    }
    RenderProductList(productsCollection.ProductResults);
}

function GetProductListByTitle(title, page, sortParameter, sortAscending) {
    var productsCollection = SearchProducts("", title, "", "", "", "", "", "", "", "", "", "", "", "", page, 12, sortParameter, sortAscending);

    switch (currentCulture.toLowerCase()) {
        case "mk-mk":
            $("#recordInfo").text("Пронајдени се [ " + productsCollection.RecordCount + " ] производи");
            break;
        case "sq-al":
            $("#recordInfo").text("Janë gjetur [ " + productsCollection.RecordCount + " ] produkteve");
            break;
    }
    if (page == 1) {
        RenderPaging(productsCollection.RecordCount, productsCollection.PageSize, page, sortParameter, sortAscending);
    }
    RenderProductList(productsCollection.ProductResults);
}

function RenderProductList(searchResults) {
    if (searchResults != null && searchResults.length > 0) {
        $("#ulProductList").html('');
        $("#productListItemTemplate").tmpl(searchResults).appendTo("#ulProductList");

        switch (currentCulture.toLowerCase()) {
            case "mk-mk":
                $("#lblCategoryInfo").text("Производи од категоријата - " + searchResults[0].CategoryName);
                break;
            case "sq-al":
                $("#lblCategoryInfo").text("PRODUKTET E TJERA NË KËTË KATEGORI - " + searchResults[0].CategoryName);
                break;
        }
    }
}

function RenderPaging(recordCount, pageSize, currentPage, sortParameter, sortAscending) {
    if (recordCount > 0) {
        var pages = Math.ceil(recordCount / pageSize);
        $("#productListPaging").paginate({
            count: pages,
            start: 1,
            display: 6,
            border: true,
            border_color: '#ccc',
            text_color: '#1f8cff',
            background_color: '#fff',
            text_hover_color: '#fff',
            background_hover_color: '#60adff',
            border_hover_color: '#1f8cff',
            images: false,
            onChange: function (page) {
                if ($("#searchBox").val() != "" && $("#searchBox").val() != "Внесете име на производ . . ." && $("#searchBox").val() != "Enter product name . . ." && $("#searchBox").val() != "Shkruani emrin e produktit . . .") {
                    GetProductListByTitle(searchText, page, sortParameter, sortAscending);
                }
                else {
                    GetProductList(page, sortParameter, sortAscending);
                }

                $(".popupTrigger").fancybox({
                    autoDimensions: false,
                    height: 350,
                    transitionIn: 'elastic',
                    transitionOut: 'elastic',
                    width: 320,
                    close: function (event, ui) {
                        ClearFieldsInMail();
                    },
                    onComplete: function () {
                        $("#btnSendMail").click(function () {
                            btnSendMail_Click();
                            ClearFieldsInMail();
                        });
                    }
                });

                $(".lnkProductListInteresedIn").click(function () {
                    var id = $(this).attr("rel");
                    GetProductById(id);
                });
            }
        });
        $("#productListPaging").css("width", $(".jPag-pages").parent('div').width() + 60 + "px");
    }
    else {
        $("#productListPaging").html('');
    }
}

function formatPrice(price) {
    return Math.ceil(price);
}

function formatPriceAsCurrency(priceValue) {
    var Num = "" + Math.ceil(priceValue);
    var dec = Num.indexOf(".");
    Num = "" + parseInt(Num);
    var temp1 = "";
    var temp2 = "";
    var count = 0;
    for (var k = Num.length - 1; k >= 0; k--) {
        var oneChar = Num.charAt(k);
        if (count == 3) {
            temp1 += ",";
            temp1 += oneChar;
            count = 1;
            continue;
        }
        else {
            temp1 += oneChar;
            count++;
        }
    }
    for (var k = temp1.length - 1; k >= 0; k--) {
        var oneChar = temp1.charAt(k);
        temp2 += oneChar;
    }
    return temp2;
}


function GetProductById(id) {
    var product;
    var args = "{ id: '" + id + "'}";
    $("#prName").html('');
    $.ajax({
        async: false,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Service/AjaxService.asmx/GetProductById",
        data: args,
        dataType: "json",
        success: function (data) {
            product = data.d;
        },
        error: function (a1) {
            alert(a1.responseText);
        }
    });
    $("#prName").append("<br /><input id='txtProductName' disabled='disabled' type='text' value=" + product.Name + " name='producttname' class='bar required' style='width: 98%; height: 20px;' />");
}


function ClientSendMail(name, email, message, productName, contact) {

    var args = "{from: '" + name + "',mail: '" + email + "',body: '" + message + "',subject: '" + "" + "',attach: '" + "" + "',prod: '" + productName + "',contact: '" + contact + "'}";

    $.ajax({
        async: true,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Service/AjaxService.asmx/SendMail",
        data: args,
        dataType: "json",
        success: function (data) {
            $("#imgMailLoader").hide();
            $("#lblSendMail").text("*Вашиот е-маил е успешно пратен!");
        },
        error: function (a1) {
        }
    });
}

function ClientSendMailMaster(name, email, message, contact) {

    var args = "{from: '" + name + "',mail: '" + email + "',body: '" + message + "',contact: '" + contact + "'}";

    $.ajax({
        async: true,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Service/AjaxService.asmx/SendMailMaster",
        data: args,
        dataType: "json",
        success: function (data) {
            $("#imgMailLoaderMaster").hide();
            $("#lblSendMailMaster").text("*Вашиот е-маил е успешно пратен!");
        },
        error: function (a1) {
        }
    });
}

function ClearFieldsInMail() {
    $("#txtIme").val('');
    $("#txtMail").val('');
    $("#txtZabeleski").val('');
    $("#prName").html('');
}

function ClearFieldsInMailMaster() {
    $("#txtImeMaster").val('');
    $("#txtMailMaster").val('');
    $("#txtZabeleskiMaster").val('');
}
