﻿function selectCategory(category) {
    $('#categoryId').val(category.CategoryId);
    $('#categoryNode').val(category.Text);

    $('#category').hide();

    $("#selectedCategory")
                .tmpl(category)
                .appendTo("#categoryDrop");

    $("#imgCloseSelectedCategory").click(function (e) {
        $('#categoryId').val('');
        requestList('');
    });


}

function selectLocation(location) {
    $('#locationId').val(location.LocationId);
    $('#country').val(location.Country);

    $('#locationBox').hide();
    $("#locationDrop").empty();

    $("#selectedLocation")
                .tmpl(location)
                .appendTo("#locationDrop");

    $("#imgCloseSelectedLocation").click(function (e) {
        $('#locationId').val('');
        requestList();
    });
}

function requestList(catPath) {
    var path = "";
    if (catPath == undefined)
        path = SUBPATH + '/List' + CATPATH;
    else
        path = SUBPATH + '/List' + catPath;


    var paramData = {};

    var locationId = $('#locationId').val();
    var country = $('#country').val();

    if (locationId != "") {
        paramData.Location = {
            "LocationId": locationId
        };
    }

    var paramStr = encode(JSON.stringify(paramData));
    if (country != "" && locationId != "" && path != "") {
        window.location = "http://" + country.toLowerCase() + ".lizta.com" + path + "?p=" + paramStr;
    }
    else {
        
        window.location.href = path + "?p=" + paramStr;
    }
}


var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";


function encode(input) {
    var output = "";
    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
    var i = 0;

    input = _utf8_encode(input);

    while (i < input.length) {

        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output +
		_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
		_keyStr.charAt(enc3) + _keyStr.charAt(enc4);

    }

    return output;
}

function _utf8_encode(string) {
    string = string.replace(/\r\n/g, "\n");
    var utftext = "";

    for (var n = 0; n < string.length; n++) {

        var c = string.charCodeAt(n);

        if (c < 128) {
            utftext += String.fromCharCode(c);
        }
        else if ((c > 127) && (c < 2048)) {
            utftext += String.fromCharCode((c >> 6) | 192);
            utftext += String.fromCharCode((c & 63) | 128);
        }
        else {
            utftext += String.fromCharCode((c >> 12) | 224);
            utftext += String.fromCharCode(((c >> 6) & 63) | 128);
            utftext += String.fromCharCode((c & 63) | 128);
        }

    }

    return utftext;
}

$(function () {



    $("#category").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: SUBPATH + "/Services/Core/Core.svc/GetCategories",
                dataType: "json",
                data: '{"term": "' + request.term + '"}',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.GetCategoriesResult, function (item) {
                        return {
                            label: item.Text + ' : ' + item.Path,
                            Path: item.Path,
                            Text: item.Text,
                            CategoryId: item.CategoryId
                        }
                    }))

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("#CategoryBusyTd").css('display', 'none');
                },
                complete: function (XMLHttpRequest, textStatus) {
                    $("#CategoryBusyTd").css('display', 'none');
                }
            })
        },
        search: function (event, ui) {
            $("#CategoryBusyTd").css('display', 'table-cell');
        },
        focus: function (event, ui) {
            return false;
        },
        select: function (event, ui) {
            selectCategory(ui.item);
            requestList(ui.item.Path.replace('\\', '/'));
            return false;
        },
        delay: 500
    });

    $("#locationBox").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: SUBPATH + "/Services/Core/Core.svc/GetLocations",
                dataType: "json",
                data: '{"term": "' + request.term + '", "country":""}',
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.GetLocationsResult, function (item) {
                        return {
                            label: item.Name + ' : ' + item.LongName + ' ' + item.Country,
                            LongName: item.LongName + ' ' + item.Country,
                            Name: item.Name,
                            LocationId: item.LocationId,
                            Country: item.Country
                        }
                    }))

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("#LocationBusyTd").css('display', 'none');
                },
                complete: function (XMLHttpRequest, textStatus) {
                    $("#LocationBusyTd").css('display', 'none');
                }
            })
        },
        search: function (event, ui) {
            $("#LocationBusyTd").css('display', 'table-cell');
        },
        focus: function (event, ui) {
            return false;
        },
        select: function (event, ui) {
            selectLocation(ui.item);
            requestList();
            return false;
        },
        delay: 500
    });


    $('#divCategoryDropItems').hide();
    $('#imgCategoryDrop').click(function (e) {
        $('#divCategoryDropItems').fadeIn();
        e.stopPropagation();
    });

    $('#divLocationSelector').hide();
    $('#imgLocationDrop').click(function (e) {
        $('#divLocationSelector').fadeIn();
        e.stopPropagation();
    });


    $("html").click(function () {
        var $target = $(event.target);

        if (!$target.is("#divCategoryDropItems") || !$target.is("#divCategoryDropItems").children()) {
            $("#divCategoryDropItems").fadeOut();
        }

        if (!$target.is("#divLocationSelector") || !$target.is("#divLocationSelector").children()) {
            $("#divLocationSelector").fadeOut();
        }
    });

    $("#divCategoryDropItems").click(function (e) {
        e.stopPropagation();
    });

    $("#divLocationSelector").click(function (e) {
        e.stopPropagation();
    });

    $('#divCategoryDropItems').position({
        of: $('#categoryDrop'),
        my: 'left top',
        at: 'left bottom',
        offset: '0 10'
    });

    $('#divLocationSelector').position({
        of: $('#locationDrop'),
        my: 'left top',
        at: 'left bottom',
        offset: '0 10'
    });

    if (typeof PageInit != 'undefined') PageInit();
});
