﻿$.fn.extend({
    replaceClass: function (fromClass, toClass) {
        return this.removeClass(fromClass).addClass(toClass);
    }
});

function openPopup(url, title, width, height) {
    $("#divIPopup div.popupHeader h2").text(title);
    $("#divIPopup div.floatContent, #divIPopup iframe").css("width", width).css("height", height);
    $("#divIPopup iframe").hide();
    $("#divIPopup iframe").attr("src", url);

    $('#divIPopup').togglePopup();
    if ($('#popup').is(":visible")) {
        if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
            $("#popup").css("width", width - 20);
        }
        $('#popup').find("input:first").focus();
        setTimeout('$("#popup iframe").show();$("#popup div.loading").hide();', 2000);

    }
}

function toggleRegisterPopup() {
    $('#divRegister').togglePopup();
    if ($('#popup').is(":visible")) {
        $('#popup').find("input:first").focus();
    }
}

$(document).ready(function () {
    $("#onJavaScript").css("visibility", "visible");
    $("#divAuthorizeInput").find("input[type=text]").first().focus();

    $("div#opaco").click(function () {
        $('#opaco').addClass('hidden').removeAttr('style');
        $('#popup').addClass('hidden');
        //$("html, body").css("overflow", "auto");
    })

    if ($.browser.msie && $.browser.version == "6.0") {
        $("div.link, span.link").hover(
            function () {
                $(this).addClass("link_hover");
            },
            function () {
                $(this).removeClass("link_hover");
            }
        )
    }

    $(".excelExport").click(function () {
        //alert($(this).nextAll("table:first").length);
        var tableSrc = $(this).nextAll("div.b-grid:has(table):first").html();
        //alert(tableSrc);
        //return;
        tableSrc = tableSrc.replace(/<a.*?>(.*?)<\/a>/ig, "$1");
        tableSrc = tableSrc.replace(/(<td.*?class=['"]{0,}onlytext['"]{0,}>)(.+?)(<\/td>)/ig, "<td>=\"$2\"$3");
        //alert(tableSrc);

        //alert(tableSrc);
        $("#exportForm").find("input#source").val(tableSrc);
        $("#exportForm").submit();
    })

    $(".tryPasswordAgain").click(function () {
        $("#divAuthorizeInput").parent().children("div").hide();
        $("#divAuthorizeInput").find("input[type=password]").each(function () { $(this).val(""); });
        $("#divAuthorizeInput").show();
        $("#divAuthorizeInput").find("input[type=password]").first().focus();
    })

    $(".tryLoginAgain").click(function () {
        $("#divAuthorizeInput").parent().children("div").hide();
        $("#divAuthorizeInput").find("input[type=text], input[type=password]").each(function () { $(this).val(""); });
        $("#divAuthorizeInput").show();
        $("#divAuthorizeInput").find("input[type=text]").first().focus();
    })

    $("#divAuthorizeInput").children("form#frmCheckUser").submit(function () {
        $("#divAuthorizeInput").hide();
        $("#divAuthorizeLoading").show();

        var url = "/log/checkuser/" + $("#txtLogin").val() + "/" + $("#txtPassword").val() + "/?stamp=" + new Date().getTime();
        $.getJSON(url, function (data) {
            var valid = (data == "1");
            var exists = (data == "0");
            if (!valid) {
                $("#divAuthorizeLoading").hide();
                if (exists) {
                    $(".lnkPasswordRecall").attr("href", $(".lnkPasswordRecall:first").attr("url") + "?email=" + $("#txtLogin").val());
                    $("#divAuthorizeIncorrectPassword").show();
                } else {
                    $("#divAuthorizeEmailNotFound div span.hintlink").attr("alt", $("#txtLogin").val()).attr("title", $("#txtLogin").val());
                    $("#divAuthorizeEmailNotFound").show();
                }
            } else {
                $("#divAuthorizeInput").children("form#frmRefresh").submit();
            }
        });

        return false;
    })

    $("#popup .divRegisterContent form input[type=radio].radioCash").live("click", function () {
        $("#popup .divRegisterContent .popupContentForm table tr.rowRegisterCompany").hide();
    })

    $("#popup .divRegisterContent form input[type=radio].radioNonCash").live("click", function () {
        $("#popup .divRegisterContent .popupContentForm table tr.rowRegisterCompany").show();
    })

    $("#popup .divRegisterContent select[name=source]").live("change", function () {
        if ($(this).val() == 10) {
            $(this).parent().find("textarea").show();
            $(this).parent().find("textarea").focus();
            $("#popup div.popupContent").scrollTop(10000);
        } else {
            $(this).parent().find("textarea").hide();
        }
    })

    $("#popup .divRegisterContent form").live("submit", function () {
        var regData = $("#popup .divRegisterContent form").serialize();
        var url = "/log/registeruser/";

        $("#popup .divRegisterContent .popupFooter").hide();
        $("#popup .divRegisterContent div.popupContent div").hide();
        $("#popup .divRegisterContent div.popupContentLoading").show();

        $.getJSON(url, regData, function (result) {
            if (result.ErrorMessage) {
                alert('Произошла ошибка при регистрации: ' + result.ErrorMessage);
            } else if (result.IsWrongCourierCode) {
                $("#popup .divRegisterContent div.popupContent div").hide();
                $(".lnkPasswordRecall").attr("href", $(".lnkPasswordRecall:first").attr("url") + "?email=" + $("#popup .divRegisterContent .popupContentForm input[name='email']").val());
                $("#popup .divRegisterContent div.popupCourierCodeNotExists").show();
            } else if (result.IsExists) {
                $("#popup .divRegisterContent div.popupContent div").hide();
                $(".lnkPasswordRecall").attr("href", $(".lnkPasswordRecall:first").attr("url") + "?email=" + $("#popup .divRegisterContent .popupContentForm input[name='email']").val());
                $("#popup .divRegisterContent div.popupContentAlreadyExists").show();
            } else {
                if (result.IsValid) {
                    $.cookie("email", result.Email, { expires: 7, path: '/' });
                    $.cookie("password", result.Password, { expires: 7, path: '/' });
                    window.location = "/log/success/";
                    //$("#popup .divRegisterContent div.popupContent div").hide();
                    //$("#popup .divRegisterContent div.popupContentFinish").show();
                } else {
                    var table = $("#popup .divRegisterContent div.popupContent table");
                    var results = result.ValidationResults;

                    $("#popup .divRegisterContent div.popupContent div").hide();
                    $("#popup .divRegisterContent .popupFooter").show();
                    $("#popup .divRegisterContent div.popupContentForm").show();

                    var props = new Array();
                    for (var propertyName in results) {
                        props.push(propertyName);
                    }

                    //var lastInvalid = "";
                    for (var index in props.reverse()) {
                        var propertyName = props[index];
                        var valid = results[propertyName];
                        //if (!valid) lastInvalid = propertyName;
                        table.find("input[name=" + propertyName + "], textarea[name=" + propertyName + "]").first().parents("tr:first").find("td.popupContentValidation")
                            .css("visibility", valid ? "hidden" : "visible")
                            .each(function () { if (!valid) $(this).parent().find("td.popupContentRowFillIn input, td.popupContentRowFillIn textarea").first().focus(); });
                    }

                    //alert(lastInvalid + " - " + table.find("input[name=" + lastInvalid + "]").length);
                    //table.find("input[name=" + lastInvalid + "]").focus();
                }
            }
        });

        return false;
    })
})
