﻿var EposStoreService;
var EposUserService;
var EposEditorService;
var EposAdminService;

function GetStoreProxy() {
    if (typeof EposStoreService == "undefined") {
        EposStoreService = new jQServiceProxy($("#urlHost").val() + "store/storews.asmx");
    }
    return EposStoreService;
}

function GetAdminProxy() {
    if (typeof EposAdminService == "undefined") {
        EposAdminService = new jQServiceProxy($("#urlHost").val() + "admin/admin.asmx");
    }
    return EposAdminService;
}

function GetEditorProxy() {
    if (typeof EposEditorService == "undefined") {
        EposEditorService = new jQServiceProxy($("#urlHost").val() + "editor/editor.asmx");
    }
    return EposEditorService;
}

function GetUserProxy() {
    if (typeof EposUserService == "undefined") {
        EposUserService = new jQServiceProxy($("#urlHost").val() + "user/userws.asmx");
    }
    return EposUserService;
}

var loaderTimerObjects = new Array();
jQuery.fn.loader = function (c) {
    var b = {
        action: "show", animate: true, delay: 500
    },
     a = $.extend(b, c);
    this.each(function () {
        var b = $(this); if (a.action == "show") {
            if (!GetTimerObject(b.attr("id"))) {
                SetTimerObject(b.attr("id"), setTimeout(function () { loader_show(a, b, c) }, a.delay));
            }
        }
        if (a.action == "hide") {
            ResetTimerObject(b.attr("id"));
            b.children(".ld_overlay").fadeOut("fast", function () { b.children(".ld_overlay").remove() }); b.children(".ld_loader").remove()
        }
    }); return this
}

function loader_show(a, b, c) {
    var d = $("<div class='ld_overlay'>&nbsp;</div>"),
            f = b.css("padding-top"), e = b.css("padding-left");
    d.width(b.outerWidth()).height(b.outerHeight()).css("position", "absolute").css("margin-top", "-" + f).css("margin-left", "-" + e).prependTo(b); var c = $("<a class='ld_loader'>&nbsp;</a>"); b.prepend(c).prepend(d);
    var g = b.outerHeight() / 2 - c.outerHeight() / 2, h = b.outerWidth() / 2 - c.outerWidth() / 2;
    c.css("margin-top", g + "px").css("margin-left", h + "px");
    a.animate && d.fadeTo("fast", .8)
}

function GetTimerObject(elementId) {
    var ret = false;
    for (var i = 0; i < loaderTimerObjects.length; i++) {
        if (loaderTimerObjects[i] != null && loaderTimerObjects[i][0] == elementId) {
            loaderTimerObjects[i][2]++;
            ret = true;
        }
    }
    return ret;
}

function SetTimerObject(elementId, timerObject) {
    var added = false;

    for (var i = 0; i < loaderTimerObjects.length; i++) {
        if (loaderTimerObjects[i] == null) {
            loaderTimerObjects[i] = new Array(elementId, timerObject, 1);
            added = true;
        }
    }
    if (!added) loaderTimerObjects.push(new Array(elementId, timerObject, 1));
}

function ResetTimerObject(elementId) {
    for (var i = 0; i < loaderTimerObjects.length; i++) {
        if (loaderTimerObjects[i] != null && loaderTimerObjects[i][0] == elementId) {
            if (loaderTimerObjects[i][2] == 1) {
                clearTimeout(loaderTimerObjects[i][1]);
                loaderTimerObjects[i] = null;
            }
            else {
                loaderTimerObjects[i][2]--;
            }
        }
    }
}
//end loader
//ajax jQuery proxy
jQServiceProxy = function (url) //constructor for the proxy
{
    this._baseURL = url + "/";
};

jQServiceProxy.prototype =
{
    _defaultErrorHandler: function (xhr, status, error) {
        alert(xhr.statusText);
    },

    CallAjax: function (method, data, fnSuccess, fnError) {
        if (!data) data = {};

        if (!fnError) fnError = this._defaultErrorHandler;

        $.ajax({
            type: "POST",
            url: this._baseURL + method,
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: fnError,
            success: function (dt) {
                var response = dt;
                /*
                if (typeof (JSON) !== "undefined" && typeof (JSON.parse) === "function")
                response = JSON.parse(dt);
                else
                response = val("(" + dt + ")");
                */
                if (response.hasOwnProperty("d"))
                    fnSuccess(response.d);
                else
                    fnSuccess(response);
            }
        });
    }
};

//convert string to url-friendly-name
function convertToUrl(input) {
    var output = "";
    var regex = new RegExp("[a-z0-9_-]", "i");

    for (var i = 0; i < input.length; i++) {
        output += regex.test(input.charAt(i)) ? input.charAt(i) : replaceChar(input.charAt(i));
    }

    while (output.indexOf("--") > -1) {
        output = output.replace("--", "-");
    }
    return output.toLowerCase();
}

function replaceChar(ch) {
    switch (ch.toLowerCase()) {
        case "é": return "e"; break;
        case "ř": return "r"; break;
        case "ť": return "t"; break;
        case "ý": return "y"; break;
        case "ú": return "u"; break;
        case "í": return "i"; break;
        case "ó": return "o"; break;
        case "ô": return "o"; break;
        case "á": return "a"; break;
        case "ä": return "a"; break;
        case "š": return "s"; break;
        case "ď": return "d"; break;
        case "ĺ": return "l"; break;
        case "ľ": return "l"; break;
        case "ž": return "z"; break;
        case "č": return "c"; break;
        case "ň": return "n"; break;
        case "ě": return "e"; break;

        default: return "-";
    }


    return "x";
}

//store product functions
function strip(price) {
    return price = price.replace(/[^\d\.-]/g, '');
}

//num - cislo, dec - pocet des. miest, thou - separator tisiciek, pnt - oddelovac des. miest, curr1 - prefix, curr2 - postfix
function formatNumber(num, dec, thou, pnt, curr1, curr2, n1, n2) {
    var x = Math.round(num * Math.pow(10, dec));
    if (x >= 0) n1 = n2 = '';
    var y = ('' + Math.abs(x)).split('');
    var z = y.length - dec;
    if (z < 0) z--;
    for (var i = z; i < 0; i++) y.unshift('0');
    if (z < 0) z = 1; y.splice(z, 0, pnt);
    if (y[0] == pnt) y.unshift('0');
    while (z > 3) { z -= 3; y.splice(z, 0, thou); }
    var r = curr1 + n1 + y.join('') + n2 + curr2;
    return r;
}

function p_pav_changed() {
    var dSymbolServer = ',';
    var currencySymbol = '€';

    var price = parseFloat(strip($("#p_price").val().replace(dSymbolServer, ".")));

    var sel = "";
    var isel = "";
    var iisel = "";

    if ($("#p_box_add").hide()) {
        $("#p_box_add").show();
        $("#p_box_added").hide();
    }

    $("input.p_attributes").each(function (i) {
        var val = $(this).val();

        if (val != "") {
            var vals = val.split("#");
            price += parseFloat(vals[2].replace(dSymbolServer, "."));
            sel += vals[6] + ": " + vals[4] + "<br/>";

            if (vals[5] != "" && vals[5].length > 6) {
                isel += "<img src=\"" + $("#scntAddress").val() + "storage/product/40_40/" + vals[5].substring(4, 6) + "/" + vals[5] + ".jpg\" alt=\"" + vals[4] + "\"/>"
            }
        }
    });

    $("#p_finalprice").html(formatNumber(price, 2, " ", ",", "", currencySymbol));
    $("#p_at_selection").html(sel);
    $("#p_at_iselection").html(isel);
    p_add_check();
}

function p_pav_radio(attId, pavId, price, quant, value, image) {
    var val = "";
    if ($("#pav_" + pavId).attr("checked")) {
        $("#p_pav_" + attId).val(attId + "#" + pavId + "#" + price + "#" + quant + "#" + value + "#" + image + "#" + $("#p_pa_title_" + attId).html()).addClass("selected");
        $("#p_pav2_" + attId).val(attId + "#" + pavId + "#" + price + "#" + quant + "#" + value + "#" + image + "#" + $("#p_pa_title_" + attId).html()).addClass("selected");
    }
    else {
        $("#p_pav_" + attId).val("").removeClass("selected");
        $("#p_pav2_" + attId).val("").removeClass("selected");
    }

    var iisel = "";
    if ($("#p_pav_" + attId).hasClass("p_rbi") && image != "") {
        iisel = "<img src=\"" + $("#scntAddress").val() + "storage/product/" + ImageSize + "/" + image.substring(4, 6) + "/" + image + ".jpg\" alt=\"" + value + "\"/>"
    }

    $("#p_pav_image_" + attId).html(iisel);
    p_pav_changed();
}

function p_pav_img(attId, pavId, price, quant, value, image) {
    $(".prodAttr img.selected").removeClass("selected");
    $("#p_pav_" + attId).val(attId + "#" + pavId + "#" + price + "#" + quant + "#" + value + "#" + image + "#" + $("#p_pa_title_" + attId).html()).addClass("selected");
    $("#pav_" + pavId).addClass("selected");
    p_pav_changed();
}

function p_pav_adv_add(attId, pavId) {
    if ($("#tx_att_" + pavId).val() > 0 & !$("#tx_att_" + pavId).hasClass("inputError")) {
        p_add_quant_id = "#tx_att_" + pavId;
        $("#p_pav_" + attId).addClass("selected").val(attId + "#" + pavId);
        $("#p_add_tocart").removeAttr("disabled");

        p_add_tocart_click()
    }
}

function p_pav_adv_recalc(elm) {
    var sub = 0;
    if (!$(elm).hasClass("inputError")) {
        var pr = $(elm).parent().prev().html().replace(",", ".");
        sub = pr * $(elm).val();
        sub = sub.toFixed(2);
    }
    $(elm).parent().next().html(sub);
}

function p_pav_dropdown(attId, val) {
    if (val == "") {
        $("#p_pav_" + attId).val("").removeClass("selected");
    }
    else {
        $("#p_pav_" + attId).val(val + "#" + $("#p_pa_title_" + attId).html()).addClass("selected");
    }
    p_pav_changed();
}

function p_add_check() {
    var allow = true;
    $("input.p_attributes").each(function (i) {
        if ($(this).hasClass("required")) {
            if (!$(this).hasClass("selected"))
            { allow = false; }
        }
    });

    if (!allow) {
        $("#p_add_tocart").attr("disabled", "disabled");
        $(p_add_quant_id).attr("disabled", "disabled");
    }
    else {
        $("#p_add_tocart").removeAttr("disabled");
        $(p_add_quant_id).removeAttr("disabled");
    }
}

function p_multi_recalc(vid) {
    validate_number("#tx_q_" + vid, true, false, false);
    if ($("#tx_q_" + vid).val() > 0 & !$("#tx_q_" + vid).hasClass("inputError")) {
        $("#p_add_tocart" + vid).removeAttr("disabled", "disabled");


    }
    else {
        $("#p_add_tocart" + vid).attr("disabled", "disabled");
    }
}

function p_add_tocart_click(row, wish) {
    if (wish == null)
        wish = false;

    var attSelector = "input.p_attributes";
    if (row) {
        p_add_quant_id = "#tx_q_" + row;
        attSelector = "#r_" + row + " input.p_attributes";

    } else { row = ""; }

    if (!$("#p_add_tocart" + row).attr("disabled")) {
        $("#p_box_notenough").hide();
        var add = true;
        var q = parseInt($(p_add_quant_id).val());
        if (p_add_check_quant) {
            var sel = true;
            var tq = parseInt($("#p_quantity").val());
            if (tq < q) {
                sel = false;
            }
            else {
                $(attSelector).each(function (i) {
                    if ($(this).hasClass("selected")) {
                        sel = true;
                        if ($(this).val().split("#")[3] < q) {
                            add = false;
                        }
                    }
                });
            }
            if (!sel) { add = false; }
        }

        if (add) {
            $("#p_box_add").loader({ action: "show" });
            var pavs = new Array();
            var i = 0;
            $(attSelector).each(function (i) {
                if ($(this).hasClass("selected")) {
                    pavs[i] = $(this).val().split("#")[1];
                    i++;
                }
            });

            var data = { pid: $("#p_productId").val(), quant: q, pavIds: pavs, wishList: wish };
            if (wish == false) GetStoreProxy().CallAjax("AddProductToCart", $.toJSON(data), p_add_tocart_added);
            else GetStoreProxy().CallAjax("AddProductToCart", $.toJSON(data), p_add_tocart_added_wish);
        }
        else {
            $("#p_box_notenough").show();
        }
    }
    else {
        alert(p_add_errMsg);
    }
}

function w_add_tocart(p, pavs, me, i) {
    var quant = $(me).parent().parent().children().children(".quant").val();
    var data = { pid: p, pavIds: (pavs == "" ? new Array() : pavs.split(",")), quant: quant, cid: i };
    GetStoreProxy().CallAjax("AddFromWishList", $.toJSON(data), w_added);
    $(me).parent().parent().remove();
}

function w_added() {
    alert("Produkt bol pridaný do vášho košíka");
}

function p_add_tocart_added(res) {
    if (res == 1) {
        $("#p_box_add").hide();
        $("#p_box_added").show();
    }
    $("#p_box_add").loader({ action: "hide" });
    if (typeof MiniCartContentUpdate == "function") {
        MiniCartContentUpdate();
    }
}

function p_add_tocart_added_wish(res) {
    if (res == 1) {
        $("#p_box_add").hide();
        $("#p_box_added_wish").show();
    }
    $("#p_box_add").loader({ action: "hide" });
    if (typeof MiniCartContentUpdate == "function") {
        MiniCartContentUpdate();
    }
}
//end store product functions

//minicart
function mc_content_update(lang, target) {
    GetStoreProxy().CallAjax("UpdateMiniCart", $.toJSON({ lang: lang }), function (res) { mc_content_loaded(target, res); });
}

function mc_content_loaded(target, res) {
    $("#" + target).html(res);
}
//end minicart

//store category
function c_pl_changeView(mode, id) {
    var input = { mode: mode, cid: $("#pl_cid" + id).val(), lang: $("#pl_lang" + id).val(), search: $("#pl_search" + id).val(),
        pg: $("#pl_page" + id).val(), pgSize: $("#pl_size" + id).val(), sort: $("#pl_sort" + id).val(), cla: $("#pl_cla" + id).val(), url: $("#urlLevel").val(),
        isMan: $("#pl_isMan" + id).val(), mName: $("#pl_mName" + id).val(), uid: id
    }

    GetStoreProxy().CallAjax("ChangeProductListView", $.toJSON(input), function (res) { c_pl_loaded(res, mode, id) });
}

function c_pl_loaded(res, mode, id) {
    var ctl = 0;
    eval("ctl=c_pl_target" + id);
    $("#" + ctl).html($.trim(res.Rows));
    $("#pager").html($.trim(res.Pager));
    $("#vb_" + id + " a").removeClass("selected");
    switch (mode) {
        case 0:
            $("#vb_" + id + " .simple").addClass("selected");
            break;
        case 1:
            $("#vb_" + id + " .default").addClass("selected");
            break;
        case 2:
            $("#vb_" + id + " .big").addClass("selected");
            break;
    }
}

function c_pagerClick(page, id) //pouziva aj producer!!!
{
    $("#pl_page" + id).val(page);
    $(".viewbar .selected").click();

}
//end store category

///JSON jQuery (de)serializer
(function ($) {
    $.toJSON = function (o) {
        /// <summary>Zmeni javascript objekt na jeho JSON reprezentaciu(a naopak).</summary>
        /// <param name="o" type="string">data s ktorymi pracujeme.</param>
        /// <returns></returns>
        if (typeof (JSON) == 'object' && JSON.stringify)
            return JSON.stringify(o); var type = typeof (o); if (o === null)
            return "null"; if (type == "undefined")
            return undefined; if (type == "number" || type == "boolean")
            return o + ""; if (type == "string")
            return $.quoteString(o); if (type == 'object') {
            if (typeof o.toJSON == "function")
                return $.toJSON(o.toJSON()); if (o.constructor === Date) {
                var month = o.getUTCMonth() + 1; if (month < 10) month = '0' + month; var day = o.getUTCDate(); if (day < 10) day = '0' + day; var year = o.getUTCFullYear(); var hours = o.getUTCHours(); if (hours < 10) hours = '0' + hours; var minutes = o.getUTCMinutes(); if (minutes < 10) minutes = '0' + minutes; var seconds = o.getUTCSeconds(); if (seconds < 10) seconds = '0' + seconds; var milli = o.getUTCMilliseconds(); if (milli < 100) milli = '0' + milli; if (milli < 10) milli = '0' + milli; return '"' + year + '-' + month + '-' + day + 'T' +
hours + ':' + minutes + ':' + seconds + '.' + milli + 'Z"';
            }
            if (o.constructor === Array) {
                var ret = []; for (var i = 0; i < o.length; i++)
                    ret.push($.toJSON(o[i]) || "null"); return "[" + ret.join(",") + "]";
            }
            var pairs = []; for (var k in o) {
                var name; var type2 = typeof k; if (type2 == "number")
                    name = '"' + k + '"'; else if (type2 == "string")
                    name = $.quoteString(k); else
                    continue; if (typeof o[k] == "function")
                    continue; var val = $.toJSON(o[k]); pairs.push(name + ":" + val);
            }
            return "{" + pairs.join(", ") + "}";
        }
    }; $.evalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(src); return eval("(" + src + ")");
    }; $.secureEvalJSON = function (src) {
        if (typeof (JSON) == 'object' && JSON.parse)
            return JSON.parse(src); var filtered = src; filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@'); filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")"); else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    }; $.quoteString = function (string) {
        if (string.match(_escapeable)) {
            return '"' + string.replace(_escapeable, function (a)
            { var c = _meta[a]; if (typeof c === 'string') return c; c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16); }) + '"';
        }
        return '"' + string + '"';
    }; var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g; var _meta = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' };
})(jQuery);

//string.format imitacia
String.prototype.format = function () { var s = this, i = arguments.length; while (i--) { s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]); } return s; };

var tb_pathToImage = "images/loader.gif";
var tb_LinkClose = "";
var tb_imgPrev = "";
var tb_imgNext = "";
var tb_animation = "fast";
var tb_stack = new Array();
var tb_url = "";
var tb_oId = ""; //overlay
var tb_wId = ""; //window
var tb_atId = ""; //ajaxtitle
var tb_cId = ""; //close
var j_oId = "#";
var j_wId = "#";
var j_atId = "#";
var j_cId = "#";
var tb_linkOver = "";
var zindex = 100;

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function () {
    tb_url = $("#cdnAddress").val();
    tb_init('a.thickbox, area.thickbox, input.thickbox'); //pass where to apply thickbox
    imgLoader = new Image(); // preload image
    imgLoader.src = tb_url + tb_pathToImage;
    tb_LinkClose = "<img src='" + tb_url + "images/close.png' alt='Close' />";
    tb_linkOver = "<img id='TB_Over' src='" + tb_url + "images/s.gif' alt='' />";
    tb_imgPrev = "<div id='TB_prev' title='Prev'></div>";
    tb_imgNext = "<div id='TB_next' title='Next'></div>";
    tb_divPrev = "<div id='TB_dprev' title='Prev'></div>";
    tb_divNext = "<div id='TB_dnext' title='Next'></div>";

});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk) {
    $(domChunk).click(function () {
        var t = this.title || this.name || null;
        var a = this.href || this.alt; var g = this.rel || false;
        tb_show(t, a, g); this.blur(); return false;
    });
    // $(domChunk).removeAttr("href");
}
//open from js
function tb_special(pi_href, title, animation) {
    var caption = title; var group = this.rel || false;
    if (animation) tb_animation = animation;
    tb_show(caption, pi_href, group);
}

function tb_show(caption, url, imageGroup) {
    try {
        var idx = 0;
        if (tb_stack.length != 0) idx = tb_stack[tb_stack.length - 1] + 1;
        tb_stack.push(idx);

        zindex = 100 + (10 * idx);
        tb_oId = "TB_overlay" + idx;
        tb_wId = "TB_window" + idx;
        tb_atId = "TB_ajaxWindowTitle" + idx;
        tb_cId = "TB_closeButton" + idx;
        var tb_ajId = "TB_ajaxContent" + idx;
        j_oId = "#" + tb_oId;
        j_wId = "#" + tb_wId;
        j_atId = "#" + tb_atId;
        j_cId = "#" + tb_cId;
        var j_ajId = "#" + tb_ajId;

        tb_createOverlay(idx);

        if (caption == null) { caption = ""; }
        $("body").append("<div id='TB_load'><img src='" + imgLoader.src + "' /></div>"); //add loader to the page
        $('#TB_load').show(); //show loader

        var baseURL;
        if (url.indexOf("?") !== -1) { //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
        } else {
            baseURL = url;
        }

        var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
        var urlType = baseURL.toLowerCase().match(urlString);
        $(j_wId).css("z-index", zindex + 2);

        if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp') {//code to show images
            var strHtml = "<a href='' id='TB_ImageOff' title='Close'>" + tb_divPrev + tb_divNext + tb_linkOver + "<img id='TB_Image' alt='' /></a><div id='TB_caption'><span></span><div id='TB_secondLine'></div></div><div id='TB_closeWindow'>"
                + "<a id='" + tb_cId + "' class='TB_closeButton' title='Close'>" + tb_LinkClose + "</a></div>"
            $(j_wId).append(tb_imgPrev + strHtml + tb_imgNext);
            tb_showImageGroup(caption, url, imageGroup);
        }
        else {//code to show html
            var queryString = url.replace(/^[^\?]+\??/, '');
            var params = tb_parseQuery(queryString);

            TB_WIDTH = (params['width'] * 1) + 30 || 730; //defaults to 730 if no paramaters were added to URL
            TB_HEIGHT = (params['height'] * 1) + 40 || 540; //defaults to 540 if no paramaters were added to URL
            ajaxContentW = TB_WIDTH - 30;
            ajaxContentH = TB_HEIGHT - 45;

            var htmHStart = "<div class='TB_title'><div id='" + tb_atId + "' class='TB_ajaxTitle'>" + caption + "</div>";
            var htmHClose = "<div class='TB_closeAjaxWindow'><a href='#' id='" + tb_cId + "' class='TB_closeButton'><img src='" + tb_url + "images/close3.gif' alt='close' /></a></div>";

            var htmHEnd = "</div>";
            var htmAjax = "<div id='" + tb_ajId + "' class='TB_ajaxContent' style='width:" + ajaxContentW + "px;height:" + ajaxContentH + "px'></div>";

            if (url.indexOf('TB_iframe') != -1) {// either iframe or ajax window		
                urlNoQuery = url.split('TB_');
                $("#TB_iframeContent").remove();
                if (params['modal'] != "true") {//iframe no modal
                    $(j_wId).append(htmHStart + htmHClose + htmHEnd + "<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;' ></iframe>");
                }
                else {//iframe modal
                    $(j_oId).unbind();
                    $(j_wId).append("<iframe frameborder='0' hspace='0' src='" + urlNoQuery[0] + "' id='TB_iframeContent' name='TB_iframeContent" + Math.round(Math.random() * 1000) + "' onload='tb_showIframe()' style='width:" + (ajaxContentW + 29) + "px;height:" + (ajaxContentH + 17) + "px;'> </iframe>");
                }
            }
            else {// not an iframe, ajax
                if ($(j_wId).css("display") != "block") {
                    if (params['modal'] != "true") {//ajax no modal
                        $(j_wId).append(htmHStart + htmHClose + htmHEnd + htmAjax);
                    }
                    else {//ajax modal
                        $(j_oId).unbind();
                        $(j_wId).append(htmHStart + htmHEnd + htmAjax);
                    }
                } else {//this means the window is already up, we are just loading new content via ajax
                    $(j_ajId)[0].style.width = ajaxContentW + "px";
                    $(j_ajId)[0].style.height = ajaxContentH + "px";
                    $(j_ajId)[0].scrollTop = 0;
                    $(j_atId).html(caption);
                }
            }

            $(j_cId).click(tb_remove);

            if (url.indexOf('TB_inline') != -1) {
                $(j_ajId).append($('#' + params['inlineId']).children());
                $(j_wId).unload(function () {
                    $('#' + params['inlineId']).append($(j_ajId).children()); // move elements back when you're finished
                });
                tb_position();
                $("#TB_load").remove();
                $(j_wId).css({ display: "block" });

                $(j_wId).draggable({ handle: ".TB_title" });
            }
            else if (url.indexOf('TB_iframe') != -1) {
                tb_position();
                if ($.browser.safari) {//safari needs help because it will not fire iframe onload
                    $("#TB_load").remove();
                    $(j_wId).css({ display: "block" });
                }
                $(j_wId).draggable({ handle: ".TB_title" });
            }
            else {
                $(j_ajId).load(url += "&random=" + (new Date().getTime()), function () {//to do a post change this load method
                    tb_position();
                    $("#TB_load").remove();
                    tb_init(j_ajId + " a.thickbox");
                    $(j_wId).css({ display: "block" });
                });
                $(j_wId).draggable();
            }




            if (!params['modal']) { document.onkeyup = function (e) { if (e == null) { keycode = event.keyCode; } else { keycode = e.which; } if (keycode == 27) { tb_remove(); } }; }
        }

    } catch (e) {
        alert(e);
        //nothing here
    }
}

function tb_createOverlay(idx) {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
        $("body", "html").css({ height: "100%", width: "100%" });
        $("html").css("overflow", "hidden");
        if (document.getElementById("TB_HideSelect" + idx) === null) {//iframe to hide select elements in ie6
            $("body").append("<iframe id='TB_HideSelect" + idx + "' class='TB_HideSelect'></iframe><div id='" + tb_oId + "' class='TB_overlay'></div><div id='" + tb_wId + "' class='TB_window'></div>");
            $(j_oId).click(tb_remove);
        }
    } else {//all others
        if ($(j_oId).length == 0) {
            if ($("body form:first")) {
                $("body form:first").append("<div id='" + tb_oId + "' class='TB_overlay'></div><div id='" + tb_wId + "' class='TB_window'></div>");
            }
            else {
                $("body").append("<div id='" + tb_oId + "' class='TB_overlay'></div><div id='" + tb_wId + "' class='TB_window'></div>");
            }
            $(j_oId).click(tb_remove);
        }
    }

    if (tb_detectMacXFF()) {
        $(j_oId).addClass("TB_overlayMacFFBGHack"); //use png overlay so hide flash
    } else {
        $(j_oId).addClass("TB_overlayBG").css("z-index", zindex); //use background and opacity
    }
    $(j_oId).fadeTo(tb_animation, 0.6);
}


function tb_showImageGroup(caption, url, imageGroup) {
    $(j_wId + " *").unbind();

    var TB_PrevCaption = "";
    var TB_PrevURL = "";
    var TB_PrevIs = false;
    var TB_NextCaption = "";
    var TB_NextURL = "";
    var TB_NextIs = false;
    var TB_imageCount = "";
    var TB_FoundURL = false;
    var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
    if (imageGroup) {
        var TB_TempArray = $("a[rel=" + imageGroup + "]").get();
        for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && !TB_NextIs); TB_Counter++) {
            var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
            if (TB_TempArray[TB_Counter].href != url) {
                if (TB_FoundURL) {
                    TB_NextCaption = TB_TempArray[TB_Counter].title;
                    TB_NextURL = TB_TempArray[TB_Counter].href;
                    TB_NextIs = true;
                }
                else {
                    TB_PrevCaption = TB_TempArray[TB_Counter].title;
                    TB_PrevURL = TB_TempArray[TB_Counter].href;
                    TB_PrevIs = true;
                }
            }
            else {
                TB_FoundURL = true;
                TB_imageCount = "Image " + (TB_Counter + 1) + " of " + (TB_TempArray.length);
            }
        }
    }

    $("#TB_caption span").html(TB_imageCount);
    $("#TB_secondLine").html(caption);

    var imgPreloader = new Image();
    imgPreloader.onload = function () {
        imgPreloader.onload = null;

        // Resizing large images
        var pagesize = tb_getPageSize();
        var x = pagesize[0] - 150;
        var y = pagesize[1] - 150;
        var imageWidth = imgPreloader.width;
        var imageHeight = imgPreloader.height;
        if (imageWidth > x) {
            imageHeight = imageHeight * (x / imageWidth);
            imageWidth = x;
            if (imageHeight > y) {
                imageWidth = imageWidth * (y / imageHeight);
                imageHeight = y;
            }
        } else if (imageHeight > y) {
            imageWidth = imageWidth * (y / imageHeight);
            imageHeight = y;
            if (imageWidth > x) {
                imageHeight = imageHeight * (x / imageWidth);
                imageWidth = x;
            }
        }
        // End Resizing


        /*
        $("#TB_window").empty().append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='" + url + "' width='" + imageWidth + "' height='" + imageHeight + "' alt='" + caption + "'/></a>"
        + "<div id='TB_caption'>" + TB_NextHTML + TB_PrevHTML + "<div id='TB_closeWindow'><a href='#' id='TB_closeButton' title='Close'>" + tb_LinkClose + "</a></div>" + caption + "<div id='TB_secondLine'>" + TB_imageCount + "</div></div>");
        */
        $(j_cId).click(tb_remove);
        $("#TB_prev").hide();
        $("#TB_next").hide();
        $("#TB_dprev").hide();
        $("#TB_dnext").hide();
        if (TB_PrevIs) {
            function goPrev() {
                tb_showImageGroup(TB_PrevCaption, TB_PrevURL, imageGroup);
                return false;
            }
            $("#TB_prev").unbind("click").click(goPrev).show();
            $("#TB_dprev").css('height', imageHeight).unbind("click").click(goPrev).show();
        }

        if (TB_NextIs) {
            function goNext() {
                tb_showImageGroup(TB_NextCaption, TB_NextURL, imageGroup);
                return false;
            }
            $("#TB_next").unbind("click").click(goNext).show();
            $("#TB_dnext").css('height', imageHeight).unbind("click").click(goNext).show();
        }

        document.onkeydown = function (e) {
            if (e == null) { keycode = event.keyCode; } else
            { keycode = e.which; } if (keycode == 27) {
                tb_remove();
            } else if (keycode == 39) {
                if (TB_NextIs) { document.onkeydown = ""; goNext(); }
            } else if (keycode == 37) { if (TB_PrevIs) { document.onkeydown = ""; goPrev(); } }
        };

        TB_WIDTH = imageWidth + 30;
        TB_HEIGHT = imageHeight + 60;

        tb_position();
        $("#TB_Image").attr("src", url).attr("width", imageWidth).attr("height", imageHeight);
        $("#TB_Over").attr("width", imageWidth).attr("height", imageHeight);
        //$("#TB_Image").animate({ width: imageWidth, height: imageHeight }, 'slow');

        $("#TB_load").remove();
        $("#TB_ImageOff").click(tb_remove);
        $(j_wId).fadeIn(tb_animation);
        //$(j_wId).css({ display: "block" }); //for safari using css instead of show
    };

    imgPreloader.src = url;

}



//helper functions below
function tb_showIframe() { $("#TB_load").remove(); $(j_wId).css({ display: "block" }); }

function tb_remove() {
    var closedId = tb_stack[tb_stack.length - 1];

    $("#TB_imageOff").unbind("click");
    $("#TB_closeButton" + closedId).unbind("click");
    $("#TB_window" + closedId).fadeOut(tb_animation, function () {
        $("#TB_window" + closedId + ',#TB_HideSelect').trigger("unload").unbind().remove();
        $("#TB_overlay" + closedId).fadeOut(tb_animation, function () {
            $("#TB_overlay" + closedId).trigger("unload").unbind().remove()
            if (tb_stack[tb_stack.length - 1] == closedId) tb_stack.pop();
        });
    });
    $("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body", "html").css({ height: "auto", width: "auto" });
        $("html").css("overflow", "");
    }
    if (typeof tb_OnClosing == 'function') {
        tb_OnClosing();
    }
    document.onkeydown = "";
    document.onkeyup = "";
    return false;
}

function tb_position() {
    $(j_wId).css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
    if (!(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
        $(j_wId).css({ marginTop: '-' + parseInt((TB_HEIGHT / 2), 10) + 'px' });
    }
}

function tb_parseQuery(query) { var P1 = {}; if (!query) { return P1; }; var P2 = query.split(/[;&]/); for (var i = 0; i < P2.length; i++) { var KeyVal = P2[i].split('='); if (!KeyVal || KeyVal.length != 2) { continue; } var key = unescape(KeyVal[0]); var val = unescape(KeyVal[1]); val = val.replace(/\+/g, ' '); P1[key] = val; } return P1; }

function tb_getPageSize() { var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de && de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de && de.clientHeight) || document.body.clientHeight; arrayPageSize = [w, h]; return arrayPageSize; }

function tb_detectMacXFF() { var u = navigator.userAgent.toLowerCase(); if (u.indexOf('mac') != -1 && u.indexOf('firefox') != -1) { return true; } }

function tb_alert(message, type, title) {
    var idx = 0;
    if (tb_stack.length != 0) idx = tb_stack[tb_stack.length - 1] + 1;

    var t = "";
    var titles = $("#hidTbAlertTitles").attr("content").split("#");
    var i = "<div class=\"tb_info\">&nbsp;</div>";

    if (title != null) t = title;

    if (type != null) {
        if (t == "") {
            if (type == "info") t = titles[0];
            else if (type == "error") t = titles[2];
            else if (type == "warning") t = titles[1];
        }

        if (type == "error") i = "<div class=\"tb_error\">&nbsp;</div>";
        else if (type == "warning") i = "<div class=\"tb_warn\">&nbsp;</div>";
    }

    message = i + "<br />" + message;

    if ($("#tb_alertBox" + idx).length > 0) {
        $("#tb_alertBox" + idx + " .tb_alert").children("span").html(message);
    }
    else {
        var div = "<div id=\"tb_alertBox" + idx + "\" style=\"display:none\"><div class=\"tb_alert\"><span>" + message + "</span><div style=\"text-align:center;margin-top:15px;\"><input id=\"tb_alert_btn" + idx + "\" type=\"button\" /></div></div></div>";
        $("body").append(div);
    }

    //resize
    var ww = $(window).width();
    var wh = $(window).height();
    var btns = $("#hidTbDialogButtons").attr("content").split("#");
    $("#tb_alertBox" + idx).css("display", "block");
    $("#tb_alert_btn" + idx).attr("value", btns[2]).unbind().bind("click", function () { tb_remove(); });
    tb_resizeBox($("#tb_alertBox" + idx + " .tb_alert").css("overflow", "inherit").css("height", "").width(350), ww, wh)

    var h = $("#tb_alertBox" + idx + " .tb_alert").height() + 10;
    var w = $("#tb_alertBox" + idx + " .tb_alert").width() + 10;
    if (h < 120) h = 150;
    $("#tb_alertBox" + idx).css("display", "none");


    tb_special("#TB_inline?height=" + h + "&width=" + w + "&inlineId=tb_alertBox" + idx, t, "fast");

}

function tb_dialog(message, funcYes, funcNo, title, buttons, customText) {
    var ans = true;
    var t = "";
    if (title) t = title;

    if ($("#tb_dialogBox").length > 0) {
        $("#tb_msg").html(message);
    }
    else {
        var div = "<div id=\"tb_dialogBox\" style=\"display:none\"><div id=\"tb_dialog\"><span id=\"tb_msg\">" + message + "</span><div style=\"text-align:center; margin-top:10px;\"><input type=\"button\" id=\"tb_a1\" /><input type=\"button\" id=\"tb_a2\" /></div></div></div>";
        $("body").append(div);
    }
    var btns = $("#hidTbDialogButtons").attr("content").split("#");
    var b1;
    var b2;

    if (customText) {
        b1 = customText.split(",")[0];
        b2 = customText.split(",")[1];
    }
    else if (buttons == "YesNo" || buttons == null) {
        b1 = btns[0];
        b2 = btns[1];
    }
    else if (buttons == "OkCancel") {
        b1 = btns[2];
        b2 = btns[3];
    }

    $("#tb_a1").attr("value", b1).unbind().bind("click", function () { tb_dialogBtn1(funcYes); });
    $("#tb_a2").attr("value", b2).unbind().bind("click", function () { tb_dialogBtn2(funcNo); }); ;

    var ww = $(window).width();
    var wh = $(window).height();

    $("#tb_dialogBox").css("display", "block");

    tb_resizeBox($("#tb_dialog").css("overflow", "inherit").css("height", "").width(400), ww, wh)

    var h = $("#tb_dialog").height() + 10;
    var w = $("#tb_dialog").width() + 10;
    if (h < 120) h = 150;
    $("#tb_dialogBox").css("display", "none");

    tb_special("#TB_inline?height=" + h + "&width=" + w + "&inlineId=tb_dialogBox&modal=true", t, "fast");
}

function tb_dialogBtn1(funcYes) {
    tb_remove();
    if (typeof funcYes != "undefined") {
        funcYes();
    }
}

function tb_dialogBtn2(funcNo) {
    tb_remove();
    if (typeof funcNo != "undefined") {
        funcNo();
    }
}

function tb_resizeBox(box, winW, winH) {
    //alert("okno H " + winH * 0.75);
    //alert("box H " +box.height());
    if (box.height() > winH * 0.75) {
        if (box.width() < winW - 120) {
            box.width(box.width() + 20);
            tb_resizeBox(box, winW, winH);
        }
        else {
            if (box.height() < winH - 120) {
                box.height(box.height() + 20);
                tb_resizeBox(box, winW, winH);
            }
            else {
                box.height(winH - 120);
                box.css("overflow", "auto");
            }
        }
    }
}


function validate_number(elm, req, dec, neg) {
    var v = $(elm).val();
    var r = null;
    var validate = false;
    if (req) {
        validate = true;
    }
    else {
        if (v == null | v.length < 1)
            validate = false;
        else
            validate = true;
    }

    if (validate) {
        if (dec) {
            if (neg)
                r = /^(\+|-)?\d+,\d{2}$/;
            else
                r = /^\d+,\d{2}$/;
        }
        else {
            if (neg)
                r = /^(\+|-)?\d+$/;
            else
                r = /^\d+$/;
        }

        if (!r.test(v))
            $(elm).addClass("inputError");
        else
            $(elm).removeClass("inputError");
    }
    else {
        $(elm).removeClass("inputError");
    }
}

function validate_text(elm) {
    var v = $(elm).val();
    if (v != null && $.trim(v).length < 1) {
        $(elm).addClass("inputError");
    }
    else {
        $(elm).removeClass("inputError");
    }
}

function validate_time(elm, req) {
    var v = $(elm).val();
    var r = null;
    var validate = false;
    if (req) {
        validate = true;
    }
    else {
        if (v == null | v.length < 1)
            validate = false;
        else
            validate = true;
    }

    if (validate) {
        r = /^([ 01][ 0-9]:[0-5][0-9]|2[0-3]:[0-5][0-9])$/;

        if (!r.test(v))
            $(elm).addClass("inputError");
        else
            $(elm).removeClass("inputError");
    }
    else {
        $(elm).removeClass("inputError");
    }
}

function formatDate(jsonDate) {
    var date = new Date(parseInt(jsonDate.substr(6)));
    return date.format("dd.MM.yyyy");
}

function formatTime(jsonDate) {
    var date = new Date(parseInt(jsonDate.substr(6)));
    return date.format("HH:mm");
}

function validate(elm, req, type, custValue, appendMsg, custMsg, appendImg, custImg) {
    //type = txt, num, decsk, decen, email, datesk, dateen, regex, none
    //append = 0:none, 1:prepend, 2:append
    //custValue = regex/string, num/allowNegative, dec/allowNegative

    var et = elm.type;
    var jMe = $(elm);
    var v = true;
    if (!req && $.trim(jMe.val()).length < 1)
        v = false;

    if (v) {
        if (type == "regex" | type == "decsk" | type == "decen" | type == "num" | type == "email" | type == "dateen" | type == "datesk") {
            var r;
            switch (type) {
                case "regex":
                    r = new RegExp(custValue);
                    break;
                case "decsk":
                    if (custValue)
                        r = /^(\+|-)?\d+,\d{2}$/;
                    else
                        r = /^\d+,\d{2}$/;
                    break;
                case "decen":
                    if (custValue)
                        r = /^(\+|-)?\d+\.\d{2}$/;
                    else
                        r = /^\d+\.\d{2}$/;
                    break;
                case "num":
                    if (custValue)
                        r = /^(\+|-)?\d+$/;
                    else
                        r = /^\d+$/;
                    break;
                case "email":
                    r = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
                    break;
            }

            if (!r.test(jMe.val()))
                v = false;
        }
    }

    if (custMsg) {
        custMsg = "<span class=\"inputMessage\">" + custMsg + "</span>";
    }

    if (v) {
        jMe.removeClass("inputError");
        if (appendMsg == 1 || appendMsg == 2)
            jMe.parent().children(".inputMessage").remove();
    }
    else {
        jMe.addClass("inputError");
        if (appendMsg == 1) {
            jMe.parent().prepend(custMsg);
        }
        else if (appendMsg == 2) {
            jMe.parent().append(custMsg);
        }
    }
    return v;
}

function validate_controls(parent, jSelector, collectErrors) {
    var jArr;
    if (parent) {
        jArr = $("#" + parent + " .custInput");
    }
    else
        jArr = $(jSelector);


    jArr.each(function () {
        $(this).keyup();
    });


}

function validate_reset(parent, jSelector) {
    var jArr;
    if (parent) {
        jArr = $("#" + parent + " .custInput");
    }
    else
        jArr = $(jSelector);


    jArr.removeClass("inputError");

}

function block_load(bid, targetElement, editor) {
    var data = { blockId: bid, enabledEditor: editor };

    GetUserProxy().CallAjax("LoadBlock", $.toJSON(data), function (res) { block_loaded(res, targetElement); });
}

function block_load_custom(data, lang, targetElement, editor) {

}

function block_loaded(res, elm) {
    $("#" + elm).html(res);
}

//blocks user functions/actions
function ContactForm_Send(bid) {
    validate_controls("cntForm_" + bid);
    if (!$("#cntForm_" + bid + " input").hasClass("inputError")) {
        var data = { blockId: bid, name: $("#txName" + bid).val(), email: $("#txEmail" + bid).val(), msg: $("#taMsg" + bid).val() };
        $("#cntForm_" + bid).loader();
        GetUserProxy().CallAjax("ContactFormSend", $.toJSON(data), function (res) { ContactForm_Sent(res, bid) });
    }
}

function ContactForm_Sent(res, bid) {
    if (res == "") {
        $("#cntForm_" + bid + " .custInput").val("");
    }
    else $("#lblMsg_" + bid).text(res);

    $("#cntForm_" + bid).loader({ action: 'hide' }).slideUp().delay(5000).slideDown();
    $("#lblMsg_" + bid).slideDown().delay(4500).slideUp();
}

function gallery_content_load(gid, targetElement) {
    var sx = $("#gs_setting_" + gid).val();
    var s = sx.split(",");

    var cnt = { data: { GalleryId: gid, CustomPath: s[0], IsGallery: s[1] }, lang: s[2], editor: s[3] };

    GetUserProxy().CallAjax("GalleryContentReload", $.toJSON(cnt), function (res) {
        block_loaded(res, targetElement);
        tb_init('#gal_' + gid + ' .thickbox');
    });
}

//autocomplete
function ac_keyup(elm, limit, method) {
    var v = $(elm).click(function () { $("#ac_pos").remove(); $(this).unbind("click"); }).val();
    var src = true;
    if (limit)
        if (v.length < limit) src = false;

    if (src) {
        var pars = { par: v, lang: $("#language").val() };
        GetUserProxy().CallAjax(method, $.toJSON(pars), function (res) {
            ac_completed(res, elm)
        });
    }
}

function ac_completed(res, elm) {
    if ($("#ac_pos").length == 0 && res.length > 0) {
        var html = "<div id='ac_pos'><div id='ac_cont'>xxx</div></div>"
        $(elm).after(html);
    }
    else {
        $("#ac_pos").remove();
    }

    var content = [];
    for (var i = 0; i < res.length; i++) {
        content.push("<div>");
        content.push(res[i][0]);
        content.push("</div>");
    }
    $("#ac_cont").html(content.join(""));
    $("#ac_cont div").click(function () { $(elm).val($(this).html()); $("#ac_pos").remove(); });
    $("#ac_pos").show();
}

function enterpressed(e, me)
{
    var srch = false;
    if (window.event)
    {
        srch = (e.keyCode == 13);
    } else if (e.which)
    {
        srch = (e.which == 13);
    }
    if (srch)
    {
        var btn = $(me).closest("div|table").parent().find(".submit");
        var x = btn.attr("href");
        if (x)
        {
            x = x.replace("javascript:", "");
            eval(x);
        }
        else
        {
            btn.click();
        }
    }

}
function highlightDays(date, dates)
{

    for (var i = 0; i < dates.length; i++)
    {
        if (new Date(dates[i]).toString() == date.toString())
        {
            return [true, 'highlight'];
        }
    }
    return [true, ''];

}
