﻿// search enter fix
var doSearch = false;
function validateSearchClick() {
    if (!doSearch)
        return false;
    return true;
}

var cartIsOpen = false;
var toggleCart = function () {
    if (cartIsOpen) {
        cartIsOpen = !cartIsOpen;
        $("#minicart").slideUp('fast');
    } else {
        cartIsOpen = !cartIsOpen;
        $("#minicart").slideDown('fast');
    }
    return false;
};

function closeCart() {
    if (cartIsOpen) {
        cartIsOpen = !cartIsOpen;
        $("#minicart").slideUp('fast');
    }
}

$(document).ready(function () {
    // gray text inside inputs before they clicked/activated
    $("input.grayText").click(function () {
        this.focus();
        this.select();
    });

    $("#topbar .input146").click(function () { doSearch = true; });

    // category menu
    $("a.L2").each(function (n, val) {
        if ($(val).hasClass("selected"))
            $(this).addClass("selected").parent().find("div.l3, div.summary").show();
    });


    // Image slider - product page
    if ($("#imgSlider").size() > 0) {

        $("#imgSlider ul").width((($("#imgSlider ul li").size() + 1) * $("#imgSlider li").outerWidth(true)));

        if ($("#imgSlider ul li").size() > 4) {
            $("#imgSlider ul li:last").prependTo($("#imgSlider ul"));
            $("#imgSlider").scrollLeft($("#imgSlider li").outerWidth(true));

            var clickInProgress = false;
            $("#slideLeft").click(function () {
                if (clickInProgress)
                    return;
                clickInProgress = true;
                $("#imgSlider ul").append($("#imgSlider ul li:last").clone());
                $("#imgSlider ul li:last").hide().prependTo($("#imgSlider ul")).animate({ width: "show" }, "slow", function () {
                    $("#imgSlider ul li:last").remove();
                    clickInProgress = false;
                });
            });
            $("#slideRight").click(function () {
                if (clickInProgress)
                    return;
                clickInProgress = true;
                $("#imgSlider ul").append($("#imgSlider ul li:first").clone());
                $("#imgSlider ul li:first").animate({ width: "hide" }, "slow", function () {
                    $(this).remove();
                    clickInProgress = false;
                });
            });
        } else {
            $("#slideLeft, #slideRight, .imageSlideExplain").hide();
        }
    }

    // Input boxes
    $("#header input[type=text]").each(function (n, val) {
        $(val).one('click', function () {
            $(this).val("");
            $(this).css({ color: '#484848' });
        });
    });

    $(".increment").click(function () {
        var num = parseInt($(this).parent().find(".productsNum").val());
        if (isNaN(num))
            num = 0;
        $(this).parent().find(".productsNum").val(num + 1);
        return false;
    });

    // Product - tabs
    if ($("#productTabs").size() > 0) {

        $("#productTabs ul a").click(function () {
            $("#productTabs .tabcontent .tab").hide();
            $("#" + $(this).attr('class')).show();
            $("#productTabs ul li").removeClass('selected');
            $(this).parent().addClass('selected');

            //$("#productTabs").height($("#productTabs .tabcontent").height());

            return false;
        });

        var myFile = document.location.toString();
        if (myFile.match('#reviews')) { // the URL contains the anchor
            $("#productTabs ul a.reviews").click();
        }
    }

    // Product - product desc
    $(".prodDesc").click(function () {
        var closePopupHtml = "<a href=\"#\" class=\"closePopup\" style=\"position: absolute; top: 0; right: 0; display: block; background-color: #eee; padding: 3px; font-weight: bold; color: #000;\">X</a>";
        TINY.box.show(closePopupHtml + $(this).parent().find("." + $(this).attr('id')).html(), 0, 450, 0, 1);
        return false;
    });

    // minicart
    $("#minicart input").keyup(function () {
        $("#minicart .cartUpdate").show();
    });

    $(".opencart, #minicart .close").click(toggleCart);

    // Add pdf icons to pdf links
    $(".attachments a").addClass("download"); //default icon, might be overridden later    
    $(".attachments a[href$='.pdf']").addClass("pdf");
    $(".attachments a[href$='.mp3'], .attachments a[href$='.wav']").addClass("audio");
    $(".attachments a[href$='.doc'], .attachments a[href$='.rtf'], .attachments a[href$='.docx']").addClass("word");
    $(".attachments a[href$='.xls'], .attachments a[href$='.xlsx'], .attachments a[href$='.csv']").addClass("excel");
    $(".attachments a[href$='.jpg'], .attachments a[href$='.png'], .attachments a[href$='.gif'], .attachments a[href$='.tif'], .attachments a[href$='.tiff'], .attachments a[href$='.bmp']").addClass("picture");
    $(".attachments a[href$='.avi'], .attachments a[href$='.flv'], .attachments a[href$='.wmv'], .attachments a[href$='.mov'], .attachments a[href$='.divx'], .attachments a[href$='.mpeg']").addClass("video");
    $(".attachments a[href$='.zip'], .attachments a[href$='.rar']").addClass("zip");


    // search
    function closeSearch() {
        $("#searchresult").slideUp('fast');
    }

    $("#search input").keyup(function () {
        search($(this).val(), 1);
    });

    $("#showAll").live('click', function () {
        $("#search input:last").click();
        return false;
    });

    $("#searchClose").live('click', function () {
        closeSearch();
    });

    // search field gray text before active
    $("input.searchBoxGray").css('color', 'gray');
    $("input.searchBoxGray").one('click', function () {
        $(this).css('color', '#000');
        $(this).val("");
    });


    // Product - stock request
    $(".lnkDeliveryContact").click(function () {
        TINY.box.show($(this).parents("div").find("#deliveryContactSchema").html(), 0, 300, 0, 1);
        return false;
    });

    // Product - share via email
    $(".shareEmail").click(function () {
        TINY.box.show($("#shareEmailSchema").html(), 0, 300, 0, 1);
        return false;
    });

    // esc - close stuff
    $(document).keydown(function (e) {
        if (e.which == 27) {  // escape, close box
            TINY.box.hide();
            closeSearch();
            closeCart();
        }
    });

    $(".closePopup").live('click', function () {
        TINY.box.hide();
        return false;
    });

    $("#ctl00_btnSearch").click(function () {
        activeSearch = "----";
    });
});

// Product - stock request
function sendStockReq() {
    $.ajax({
        type: "POST",
        url: "/AbcService.asmx/StockRequest",
        data: "{'prodno':'" + $("#tinybox .cProdNo").text() + "', 'name': '" + $("#tinybox .cName").val() + "', 'phone':'" + $("#tinybox .cPhone").val() + "', 'email':'" + $("#tinybox .cEmail").val() + "', 'comment':'" + $("#tinybox .cComment").val() + "', 'wid':'" + $('input[id*="hiddenWid"]').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(r) {

        }
    });
    TINY.box.hide();
    return false;
}

// Product - stock request
function sendShareEmail() {
    $.ajax({
        type: "POST",
        url: "/AbcService.asmx/Share",
        data: "{'sender':'" + $("#tinybox .shareSender").val() + "', 'receiver': '" + $("#tinybox .shareReceiver").val() + "', 'url':'" + window.location + "', 'title':'" + document.title + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {

        }
    });
    TINY.box.hide();
    return false;
}

var activeSearch = "";
function search(q, websiteID){
    if(q == activeSearch)
        return;
        
    $("#searchresult").html('<div class="searchBottom"><a href="#" id="showAll">Se alle resultatene</a> - <a href="#" id="searchClose">Lukk</a></div>');
    activeSearch = q;
    
    if(q == ""){
        $("#searchresult").slideUp('fast');
        return;
    }
    
    setTimeout(function(){
        if(activeSearch == q){
            $.ajax({
                type: "POST",
                url: "/ECommerceService.asmx/Search",
                data: "{'q':'" + q + "', 'websiteID': '" + $("#websiteID").text() + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (r) {

                    if(activeSearch == q){
                        if (r.d!=null && r.d.length>0) {
                            
                            $("#searchresult").slideDown('fast');
                            
                            for(var i = 0; r.d.length>i; i++){
                                var ingress = r.d[i].Ingress.length>50 ? r.d[i].Ingress.substr(0,50)+"..." : r.d[i].Ingress;
                                var image = r.d[i].Image.length>0 ? r.d[i].Image : "/App_Themes/ABC/images/product_noimage.png";
                                $("#searchresult").prepend('<div><table><tr><td style="width: 61px; height: 61px; background-color: #fff; vertical-align: middle; text-align: center"><a href="' + r.d[i].URL + '"><img src="' + image + '" alt="" style="max-width:60px; max-height: 40px;" /></a></td><td style="padding-bottom: 10px; padding-left: 5px"><h3><a href="' + r.d[i].URL + '">' + r.d[i].Title + '</a></h3>' + ingress + '</td></tr></table></div>');
                            }
                        } else {
                            $("#searchresult").slideUp('fast');
                        }
                    }
                    
                    //if(activeSearch != q)
                    //    console.log("search cancelled for: " + q);
                    
                }
            });
        } //else 
            //console.log("search not sent for: " + q);
    }, 300);
}
