// JavaScript Document for powersearch
/** Coding by Webopius Ltd. 2010
** www.webopius.com
*/

var iPowersearch = {

    init: function() {
        return;
    },

    attachStylesheet: function(href) {
        return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');
    }
};

var iPowerSearchString = '';
var quickviewStatus = 0;

$(document).ready(function() {
    iPowersearch.init();
    $("#ctl00_ctrlSearch_SearchText").change(function() {
        searchchanged();
    });

    $("#ctl00_ctrlSearch_SearchText").keydown(function(event) {
        if (event.keyCode == '13') {
            event.preventDefault();
        }
    });

    $("#ctl00_ctrlSearch_SearchText").keyup(function(event) {
        searchchanged();
    });

    $cook = getCookie("powersearch");
    if ($cook != "") {
        $("#ctl00_ctrlSearch_SearchText").val($cook);
    }

});


$(function() {
    $("a#clickMe").click(function() {
        oldsearchchanged($("#ctl00_ctrlSearch_SearchTextnew").val());
    });
});

function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
}

function searchchanged() {
    var $searchfor = $("#ctl00_ctrlSearch_SearchText").val();
    document.cookie = 'powersearch=' + $searchfor;

    if ($searchfor == iPowerSearchString) { return; }
    if ($searchfor.length < 3) { return; }

    $typefilter = "0";

    leftmenu();
    powersearch($searchfor, $typefilter, 0, 99999, 1, 1, 1);
    //setclick();

    iPowerSearchString = $searchfor;
}

function oldsearchchanged($searchfor) {
    document.cookie = 'powersearch=' + $searchfor;

    if ($searchfor == iPowerSearchString) { return; }
    if ($searchfor.length < 3) { return; }

    $typefilter = "0";

    leftmenu();
    powersearch($searchfor, $typefilter, 0, 99999, 1, 1, 1);
    //setclick();

    iPowerSearchString = $searchfor;
}

function powersearch($searchstr, $typeid, lowprice, highprice, $sortid, $currpage, $first) {
    if (typeof intervalId != 'undefined') {
        clearInterval(intervalId); // stop the hompage image rotates
    }

    //alert($searchstr);

    $.ajax({
        type: "POST",
        url: "WebService.asmx/GetPowerSearch",
        data: "{'low':'" + lowprice + "','high':'" + highprice + "','manufacturerid':'" + $typeid + "','sort':'" + $sortid + "','page':'" + $currpage + "','Search_String':'" + $searchstr + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {

            var prods = msg.d;

            var pobj = jQuery.parseJSON(prods);

            var searchhtml = "<h1>Search results for: " + $searchstr + "</h1>";

            searchhtml += "<div id=\"quickview\"><a id=\"quickviewClose\">x</a>";
            searchhtml += "<div id=\"quickviewpage\">quickview</div>";
            searchhtml += "</div><div id=\"quickviewBackground\"></div>";

            // Now do the summary stats and paging
            var stats = pobj.products.statistics[0];

            if (pobj.products.searchman.length > 0) {
                searchhtml += "<br /><h2><b>Matching Brands / Manufacturers</b> (Click below to view):</h2>";
                searchhtml += "<div class=\"brand_names\">";
                $.each(pobj.products.searchman, function(i, k) {
                    searchhtml += "<code><a href=\"m-" + k.searchmanid + "-xyz.aspx\">" + k.searchmanname + "</a></code> ";
                });
                searchhtml += "</div>";
            }

            searchhtml += "<div class=\"headrow\"><b>";
            searchhtml += stats.totalproducts + " product matches found (Searched item may also be listed under a <a href=\"/e-brands.aspx\">Brand/Manufacturer</a>). ";
            searchhtml += paginator($currpage, stats.totalpages);
            searchhtml += "</b></div>";

            var item = 1;

            $.each(pobj.products.product, function(i, k) {
                /* Image check */
                var img = "/App_Themes/skin_1/images/nopictureicon.gif";
                var urlimg = k.image;

                var ehtml = '<div class="item">';

                ehtml += "<a href=\"p-" + k.productid + "-xyz.aspx\"><img src=\"" + urlimg + "\"/></a> ";
                ehtml += "<br />" + k.manufacturer + "<br />";
                ehtml += "SKU " + k.sku + "<br />";
                if (k.size != "") {
                    ehtml += k.size + "<br />";
                }
                ehtml += "<a href=\"p-" + k.productid + "-xyz.aspx\" class=\"desc\">" + k.productname + "</a> ";
                ehtml += "<div class=\"price\">" + k.productprice + "</div>";

                ehtml += "<a href=\"#\" onclick=\"psaddtocart(" + k.productid + "," + k.variantid + ",1)\" class=\"blue_btn\"><span>Buy Now</span></a>";
                //ehtml +="<a href=\"/addtocart.aspx?Quantity=1&ProductID=" + k.productid + "&VariantID=" + k.variantid + "&returnurl=temp-p-" +  k.productid +".aspx?addtocart=1\" class=\"blue_btn\"><span>Buy Now</span></a>";
                ehtml += '</div>';

                if (item == 1) { searchhtml += "<div class=\"row\">"; }

                searchhtml += ehtml;

                item++;
                if (item == 5) { searchhtml += "</div>"; item = 1; }
            });

            if (item != 1) { searchhtml += "</div>"; }

            // Render the search content
            $(".right_col").html(searchhtml);

            // Only show the type ids contained in the result set

            var manhtml = "";
            if ($typeid == 0) {
                manhtml += "<li id=\"search-type-0\" class=\"checked\">All suppliers</li>";
            } else {
                manhtml += "<li id=\"search-type-0\" class=\"unchecked\">All suppliers</li>";
            }

            $.each(pobj.products.productman, function(i, k) {
                var chk = "unchecked";
                if (k.productmanid == $typeid) {
                    chk = "checked";
                }
                manhtml += "<li id=\"search-type-" + k.productmanid + "\" class=\"" + chk + "\">" + k.productmanname + "</li>";
            });

            $('ul.suppliers').html(manhtml);

            $("ul.searchfilter ul li").unbind();
            $("ul.searchfilter a").unbind();
            setclick();



        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
            alert(thrownError);
        }

    });
    return null;
}

function leftmenu() {
    var lhtml = "";
    lhtml += "<h2>Search Filter</h2>";
    lhtml += "<ul class=\"searchfilter searchblock\">";
    lhtml += "<ul></ul>";
    lhtml += "</ul>";

    lhtml += "<ul class=\"searchfilter\">";
    lhtml += "<a href=\"#\" class=\"expanded\"><h4>Prices</h4></a>";
    lhtml += "<ul>";
    lhtml += "<li id=\"search-price-0\" class=\"unchecked\">All prices</li>";
    lhtml += "<li id=\"search-price-1\" class=\"unchecked\">up to &pound;5</li>";
    lhtml += "<li id=\"search-price-2\" class=\"unchecked\">&pound;5 to &pound;10</li>";
    lhtml += "<li id=\"search-price-3\" class=\"unchecked\">&pound;10 to &pound;15</li>";
    lhtml += "<li id=\"search-price-4\" class=\"unchecked\">&pound;15 to &pound;20</li>"
    lhtml += "<li id=\"search-price-5\" class=\"unchecked\">&pound;20+</li>"
    lhtml += "</ul></ul>";

    lhtml += "<ul class=\"searchfilter\">";
    lhtml += "<a href=\"#\" class=\"expanded\"><h4>Sort Results</h4></a>";
    lhtml += "<ul>";
    lhtml += "<li id=\"search-sort-1\" class=\"unchecked\">Name A-Z</li>";
    lhtml += "<li id=\"search-sort-2\" class=\"unchecked\">Name Z-A</li>";
    lhtml += "<li id=\"search-sort-3\" class=\"unchecked\">Price Low to High</li>";
    lhtml += "<li id=\"search-sort-4\" class=\"unchecked\">Price High to Low</li>"
    lhtml += "</ul></ul>";

    lhtml += "<ul class=\"searchfilter\">";
    lhtml += "<a href=\"#\" class=\"expanded\"><h4>Suppliers</h4></a>";
    lhtml += "<ul class=\"suppliers\">";
    lhtml += "<li id=\"search-type-0\" class=\"unchecked\">All suppliers</li>";
    lhtml += "</ul></ul>";

    $('.left_navi').html(lhtml);
}

function setclick() {
    $("ul.searchfilter ul li").click(function() {
        if ($(this).is(".checked")) {
            $(this).attr("class", "unchecked");
        } else {
            $(this).siblings().attr('class', 'unchecked');
            $(this).attr("class", "checked");
        }
        prepfilter(1);
    });

    $("ul.searchfilter a").click(function() {

        if ($(this).is(".expanded")) {
            $(this).attr("class", "collapsed");
            $(this).next("ul").hide();
        } else {
            $(this).attr("class", "expanded");
            $(this).next("ul").show();
        }
    });

}

// Bring up the quick view dialog

function quickview($productid) {

    if (quickviewStatus == 0) {
        $("#quickviewpage").html("<div class=\"spinner\"><img src=\"/App_themes/Skin_1/images/smspinner.gif\"/></div>");

        $.get("CUSTquickview.aspx?productid=" + $productid + "&amp;searchterm=" + $(".search_box").val(), function(data) {
            $("#quickviewpage").html(data);
        });

        $("#quickviewBackground").css({
            "opacity": "0.5"
        });
        $("#quickviewBackground").fadeIn("fast");
        $("#quickview").fadeIn("fast");
        quickviewStatus = 1;
    }

    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#quickview").height();
    var popupWidth = $("#quickview").width();
    //centering
    $("#quickview").css({
        "position": "absolute",
        "top": windowHeight / 2 - popupHeight / 2 + $(document).scrollTop(),
        "left": windowWidth / 2 - popupWidth / 2
    });
    //only need force for IE6

    $("#quickviewBbackground").css({
        "height": windowHeight
    });

    $("#quickviewClose").click(function() {
        quickviewClose();
    });
    $("#quickviewBackground").click(function() {
        quickviewClose();
    });

}

function quickviewClose() {

    if (quickviewStatus == 1) {
        $("#quickviewBackground").fadeOut("slow");
        $("#quickview").fadeOut("slow");
        quickviewStatus = 0;
    }
}

// Ajax addtocart

function psaddtocart($productid, $variantid, $qty) {
    //quickviewClose();

    $(".right_col").mask("Adding the product to your basket");
    var $url = "addtocart.aspx?Quantity=" + $qty + "&ProductID=" + $productid + "&VariantID=" + $variantid + "&returnurl=/shoppingcart.aspx";

    $.ajax({
        url: $url,
        success: function(data) {

            nutrishowcart(1); // Call external minicart function to re-populate cart
            $(".right_col").unmask();

        }
    });

}

function prepfilter($page) {
    $searchfilter = "";
    $typeid = "0";
    $priceid = "0";
    $sortid = "1";

    $('ul.searchfilter:gt(0) ul li.checked').each(function(index) {
        $searchfilter += '<li id="' + $(this).attr('id') + '" class="checked">' + $(this).html() + '</li>';
        var id = $(this).attr("id");
        if (id.indexOf("-type-") != -1) {
            id = id.replace("search-type-", "");
            $typeid = id;
        }
        if (id.indexOf("-price-") != -1) {
            id = id.replace("search-price-", "");
            $priceid = id;
        }
        if (id.indexOf("-sort-") != -1) {
            id = id.replace("search-sort-", "");
            $sortid = id;
        }
    });

    $("ul.searchblock ul").html($searchfilter);

    var lowprice = 0;
    var highprice = 9999;
    switch ($priceid) {
        case '1': lowprice = 0; highprice = 5; break;
        case '2': lowprice = 5; highprice = 10; break;
        case '3': lowprice = 10; highprice = 15; break;
        case '4': lowprice = 15; highprice = 20; break;
        case '5': lowprice = 20; highprice = 9999; break;

    }

    // alert($typeid+"-"+$priceid+"-"+$sortid);
    var $searchfor = $("#ctl00_ctrlSearch_SearchText").val();

    $('html, body').scrollTop(0);

    powersearch($searchfor, $typeid, lowprice, highprice, $sortid, $page, 0);
}

function changepage($newpage) {
    prepfilter($newpage);
}

function paginator(currpage, totalpages) {
    var thispage = Number(currpage);
    if (totalpages < 2) return "";

    phtml = "<ul  class=\"paginator\">";
    phtml += "<li>Page</li>";

    if (currpage > 1) {
        phtml += "<li class=\"prev\" id=\"search-page-" + (thispage - 1) + "\"><a href=\"#\" onclick=\"changepage(" + (thispage - 1) + ")\">&laquo;</a></li>"
    }

    skipleft = false;
    skipright = false;

    for (i = 1; i <= totalpages; i++) {
        if (i == thispage) {
            phtml += "<li class=\"thispage\">" + i + "</li>";
            continue;
        }

        if ((i == 1) || (i == totalpages) || (i == (thispage - 2)) || (i == (thispage - 1)) || (i == (thispage + 1)) || (i == (thispage + 2))) {

            phtml += "<li id=\"search-page-" + i + "\"><a href=\"#\" onclick=\"changepage(" + i + ")\">" + i + "</a></li>";
            continue;
        }

        if ((i < thispage) && (!skipleft)) {
            skipleft = true;
            phtml += "<li class=\"break\">...</li>";
        }

        if ((i > thispage) && (!skipright)) {
            skipright = true;
            phtml += "<li class=\"break\">...</li>";
        }


    }

    if (currpage < totalpages) {
        phtml += "<li class=\"next\" id=\"search-page-" + (thispage + 1) + "\"><a href=\"#\" onclick=\"changepage(" + (thispage + 1) + ")\">&raquo;</a></li>"
    }


    return phtml;
}


