﻿function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
        completeNotify();
    }
}

$(function() {
    UsedCurrency();
    AdvertNotes();
    BtnFilter();
    NavigationClick(); //Event handler for navigation click event
    RegionsDropClick();
});

//Event handler for currency change event
function UsedCurrency() {
    $("li[id$=liUsedCurency1]").click(function() {
        $("input[id$=hCurrActiveSign]").val($("input[id$=hCurr1Sign]").val());
        ChangeFilterPriceRange("curr1");
        $("li[id$=liUsedCurency1]").addClass("cur");
        $("li[id$=liUsedCurency2]").removeClass("cur");
        $("li[id$=liUsedCurency3]").removeClass("cur");
        ChangePrice("curr1");
        //$("#spanCurIcon").html($(this).children().html());
        $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&currency=curr1", function() {
        });
    });
    $("li[id$=liUsedCurency2]").click(function() {
        $("input[id$=hCurrActiveSign]").val($("input[id$=hCurr2Sign]").val());
        ChangeFilterPriceRange("curr2");
        $("li[id$=liUsedCurency2]").addClass("cur");
        $("li[id$=liUsedCurency1]").removeClass("cur");
        $("li[id$=liUsedCurency3]").removeClass("cur");
        ChangePrice("curr2");
        //$("#spanCurIcon").html($(this).children().html());
        $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&currency=curr2", function() {
        });
    });
    $("li[id$=liUsedCurency3]").click(function() {
        $("input[id$=hCurrActiveSign]").val($("input[id$=hCurr3Sign]").val());
        ChangeFilterPriceRange("curr3");
        $("li[id$=liUsedCurency3]").addClass("cur");
        $("li[id$=liUsedCurency2]").removeClass("cur");
        $("li[id$=liUsedCurency1]").removeClass("cur");
        ChangePrice("curr3");
        //$("#spanCurIcon").html($(this).children().html());
        $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&currency=curr3", function() {
        });
    });
}

//Event handler for filter search click event
function BtnFilter() {
    $("input[id$=btnFilterCorrect]").click(function() {
        var errors = "";
        var priceFrom = parseInt($("input[id$=inputStartPrice]")[0].value.replaceAll(" ", ""));
        var priceTo = parseInt($("input[id$=inputEndPrice]")[0].value.replaceAll(" ", ""));
        if (priceFrom > priceTo) {
            errors += "Начальная цена должна быть меньше конечной.<br />";
            $("*[id$=inputStartPrice]").attr("style", "border:solid 1px #ffab95;");
            $("*[id$=inputEndPrice]").attr("style", "border:solid 1px #ffab95;");
        }

        var yearFrom = parseInt($("select[id$=ddlFilterYearFrom]")[0].value);
        var yearTo = parseInt($("select[id$=ddlFilterYearTo]")[0].value);
        if (yearFrom > yearTo) {
            errors += "Начальный год должен быть меньше конечного.<br />";
            $("*[id$=ddlFilterYearFrom]").attr("style", "border:solid 1px #ffab95;");
            $("*[id$=ddlFilterYearTo]").attr("style", "border:solid 1px #ffab95;");
        }

        if (errors != "") {
            $("input[id$=btnFilterCorrect]").attr("disabled", "disabled");
            $(".h-carfilter-ctrls").append('<ul id="ulFilterMessage" class="g-multipart"><li><span style="color:#ff0000;" id="spanFilterError"><br />' + errors + '</span></li></ul>');
            $("ul[id=ulFilterMessage]").fadeOut(4000, function() {
                $("input[id$=btnFilterCorrect]").attr("disabled", "");
                $("ul[id=ulFilterMessage]").remove();
                $("*[id$=inputStartPrice]").attr("style", "border:solid 1px #999999;");
                $("*[id$=inputEndPrice]").attr("style", "border:solid 1px #999999;");
                $("*[id$=ddlFilterYearFrom]").attr("style", "border:solid none none;");
                $("*[id$=ddlFilterYearTo]").attr("style", "border:solid none none;");
            });
            return false;
        }
    });
}

//Event handler for price range changes
function ChangeFilterPriceRange(currency) {
    if ($("*[id$=hCurr1Value]")[0] != null && $("*[id$=hCurr2Value]")[0] != null && $("*[id$=hCurr3Value]")[0] != null && $("input[id$=inputStartPrice]")[0] != null && $("input[id$=inputEndPrice]")[0] != null) {
        var curr1Value = parseFloat($("*[id$=hCurr1Value]")[0].value);
        var curr2Value = parseFloat($("*[id$=hCurr2Value]")[0].value);
        var curr3Value = parseFloat($("*[id$=hCurr3Value]")[0].value);
        var oldCurrency = "";
        var fromValue = parseInt($("input[id$=inputStartPrice]")[0].value.replaceAll(" ", ""));
        var toValue = parseInt($("input[id$=inputEndPrice]")[0].value.replaceAll(" ", ""));
        //var min = parseInt($("*[id$=hPriceLeftLimit]")[0].value);
        //var max = parseInt($("*[id$=hPriceRightLimit]")[0].value);
        if ($("li[id$=liUsedCurency1]").hasClass("cur")) { oldCurrency = "curr1" }
        else if ($("li[id$=liUsedCurency2]").hasClass("cur")) { oldCurrency = "curr2" }
        else if ($("li[id$=liUsedCurency3]").hasClass("cur")) { oldCurrency = "curr3" }

        if (currency == "curr1") {
            if (oldCurrency == "curr2") {
                fromValue = Math.round((curr2Value / curr1Value) * fromValue);
                toValue = Math.round((curr2Value / curr1Value) * toValue);
                //min = Math.round((curr2Value / curr1Value) * min);
                //max = Math.round((curr2Value / curr1Value) * max);
            }
            else if (oldCurrency == "curr3") {
                fromValue = Math.round(curr3Value / curr1Value * fromValue);
                toValue = Math.round(curr3Value / curr1Value * toValue);
                //min = Math.round(curr3Value / curr1Value * min);
                //max = Math.round(curr3Value / curr1Value * max);
            }
            min = $("*[id$=hPriceLeftLimit]")[0].value.split("_")[0];
            max = $("*[id$=hPriceRightLimit]")[0].value.split("_")[0];
        }
        else if (currency == "curr2") {
            if (oldCurrency == "curr1") {
                fromValue = Math.round((curr1Value / curr2Value) * fromValue);
                toValue = Math.round((curr1Value / curr2Value) * toValue);
                //min = Math.round((curr1Value / curr2Value) * min);
                //max = Math.round((curr1Value / curr2Value) * max);
            }
            else if (oldCurrency == "curr3") {
                fromValue = Math.round(curr3Value / curr2Value * fromValue);
                toValue = Math.round(curr3Value / curr2Value * toValue);
                //min = Math.round(curr3Value / curr2Value * min);
                //max = Math.round(curr3Value / curr2Value * max);
            }
            min = $("*[id$=hPriceLeftLimit]")[0].value.split("_")[1];
            max = $("*[id$=hPriceRightLimit]")[0].value.split("_")[1];
        }
        else if (currency == "curr3") {
            if (oldCurrency == "curr1") {
                fromValue = Math.round((curr1Value / curr3Value) * fromValue);
                toValue = Math.round((curr1Value / curr3Value) * toValue);
                //min = Math.round((curr1Value / curr3Value) * min);
                //max = Math.round((curr1Value / curr3Value) * max);
            }
            else if (oldCurrency == "curr2") {
                fromValue = Math.round((curr2Value / curr3Value) * fromValue);
                toValue = Math.round((curr2Value / curr3Value) * toValue);
                //min = Math.round((curr2Value / curr3Value) * min);
                //max = Math.round((curr2Value / curr3Value) * max);
            }
            min = $("*[id$=hPriceLeftLimit]")[0].value.split("_")[2];
            max = $("*[id$=hPriceRightLimit]")[0].value.split("_")[2];
        }

        $("*[id$=inputStartPrice]")[0].value = fromValue;
        $("*[id$=inputEndPrice]")[0].value = toValue;
        $("*[id$=hOneLeftLimit]")[0].value = min;
        $("*[id$=hOneRightLimit]")[0].value = max;

        if ($("input[id$=hTrackPostback]")[0] != null) {
            ReInitPrice(false);
        }
        else {
            ReInitPrice(true);
        }
    }
}

//Event handler for prices switch
function ChangePrice(currency) {
    if (currency == "curr1") {
        $("*[class$=curCurr2]").hide();
        $("*[class$=curCurr3]").hide();
        $("*[class*=curCurr1]").show();
    }
    else if (currency == "curr2") {
        $("*[class$=curCurr1]").hide();
        $("*[class$=curCurr3]").hide();
        $("*[class*=curCurr2]").show();
    }
    else {
        $("*[class$=curCurr1]").hide();
        $("*[class$=curCurr2]").hide();
        $("*[class*=curCurr3]").show();
    }
}

//Handlers for starred advert notes
function AdvertNotes() {
    $("span[id^=spanStar]").click(function() {
        var id = this.id.split("_")[1];

        if ($("span[id=spanStar_" + id + "]").hasClass("link-fave-on") || $("span[id=spanStar_" + id + "]").hasClass("b-star-on")) {
            $("span[id=spanStar_" + id + "]").removeClass("link-fave-on");
            $("span[id=spanStar_" + id + "]").removeClass("b-star-on");
            $("span[id=spanStar_" + id + "] span").html("Добавить в избранное");
            $("#liFaveAdvert_" + id).remove();
            var newCount = parseInt($("*[id*=topNavFaveCount]").html()) - 1;
            if (newCount == 0) {
                $("div[class=h-faves]").attr("style", "display:none;");
                $("*[id*=topNavFaveCount]").html("");
                $("#topNavFaveContainer").attr("style", "display:none;");
                $("#dtFave").addClass("tn-item-empty");
            }
            else {
                $("*[id*=topNavFaveCount]").html(newCount.toString());
            }
            $.get("/jQueryAjaxRequest.aspx?starred=false&ids=" + id, function() {
                GetFave();
            });
        }
        else {
            $("span[id=spanStar_" + id + "]").addClass("link-fave-on");
            $("span[id=spanStar_" + id + "]").addClass("b-star-on");
            $("span[id=spanStar_" + id + "] span").html("Удалить из избранного");

            var newCount;
            if ($("*[id*=topNavFaveCount]").html() == "") {
                newCount = 1;
                $("#dtFave").removeClass("tn-item-empty");
            }
            else
                newCount = parseInt($("*[id*=topNavFaveCount]").html()) + 1;

            if (newCount == 1) {
                $("#topNavFaveContainer").removeAttr("style");
                $("div[class=h-faves]").removeAttr("style");
            }

            $("*[id*=topNavFaveCount]").html(newCount.toString());
            $.get("/jQueryAjaxRequest.aspx?starred=true&ids=" + id, function() {
                GetFave();
            });
        }
    });
}

function GetFave() {
    $.get("/FavoritesAdverts.ashx", function(data) {
        $("#ulTopNavFaves").html(data);
    });
}

//--------------item.aspx
function ShowMorePhoto() {
    $("#divPhotos").attr("class", "th th-open");
}
function CheckPhoto(obj) {
    $("*[class *=photo cur]").removeClass("cur");
    var k = $(obj).children().children().children().children().attr("src").replace("/small", "/big");
    $("*[id $=imgTitlePhoto]").attr("src", k);
    $(obj).addClass("cur");
    galleryPhotosCurrent = parseInt($(obj).attr('id').substr($(obj).attr('id').length - 1));
}

//New Header (Countries, Search and other)
$(function() {
    $("#searchText").unbind("keydown").keydown(function(e) {
        var keynum;
        if (window.event) // IE
            keynum = e.keyCode;
        else if (e.which) // Netscape/Firefox/Opera
            keynum = e.which;
        if (keynum == 13 && $(this).val() == "")
            return false;
        else
            return keynum;
    });
});

$(document).bind("mousedown", function() {
    $("#aspnetForm").removeAttr("onsubmit");
    ResetPopups();
    HideNavigation();
});

function ResetPopups() {
    $('#divCountry').removeClass('tn-region-open');
    $('#divUser').removeClass('b-usernav-open');
    $('#divSearch').removeClass('tn-search-open');
    $('#divFave').removeClass('tn-fave-open');
    $("#dlArticleBookmark").removeClass("b-social-bkmrk-open");
}

function CountryClick() {
    HideNavigation();
    $('#divUser').removeClass('b-usernav-open');
    $('#divSearch').removeClass('tn-search-open');
    $('#divFave').removeClass('tn-fave-open');
    $('#divCountry').toggleClass('tn-region-open');
    $("#divCountry").mousedown(function() { return false });
}

function FaveClick() {
    HideNavigation();
    $('#divCountry').removeClass('tn-region-open');
    $('#divUser').removeClass('b-usernav-open');
    $('#divSearch').removeClass('tn-search-open');
    if ($("#spanFaveEnabler").hasClass("drop"))
        $('#divFave').toggleClass('tn-fave-open');
    $("#divFave").mousedown(function() { return false });
}

function UserClick() {
    HideNavigation();
    $('#divCountry').removeClass('tn-region-open');
    $('#divSearch').removeClass('tn-search-open');
    $('#divFave').removeClass('tn-fave-open');
    $('#divUser').toggleClass('b-usernav-open');
    $("#divUser").mousedown(function() { return false });
}

function SearchClick() {
    HideNavigation();
    $('#divCountry').removeClass('tn-region-open');
    $('#divUser').removeClass('b-usernav-open');
    $('#divFave').removeClass('tn-fave-open');
    $('#divSearch').toggleClass('tn-search-open');
    $("#divSearch").mousedown(function() { $('#searchtext').focus(); return false });
    $('input#searchText').focus();
}
//End New Header

//Navigation (Green Line)
function NavigationClick() {
    $('span[id*=spanDropNav]').click(function() {
        ResetPopups();
        var num = this.id.substr(this.id.length - 1);
        var divMenuId = '#divDropNavB_' + num;
        var spanDropArrowId = '#spanDropNav_' + num;
        var divMenu = $(divMenuId);
        var spanDropArrow = $(spanDropArrowId);

        var isOpen = spanDropArrow.hasClass('darr-open');

        $('div[id*=divDropNavB]').hide();
        $('span[id*=spanDropNav]').removeClass('darr-open');

        if (!isOpen) {
            spanDropArrow.addClass('darr-open');
            divMenu.show();

            var offset = spanDropArrow.parent().offset();
            divMenu.css('left', offset.left - $('#maincontent').offset().left + 3 + 'px');
            //var props = '';
            //for (prop in offset)
            //    props += prop + ': ' + offset[prop] + '\n';
        }

        spanDropArrow.parent().mousedown(function() { return false; });
        divMenu.mousedown(function() { return false; });
    });
}

function RegionsDropClick() {
    $('#spanRegionsDrop').click(function() {
        ResetPopups();
        var divMenu = $('#divRegionsList');
        var spanRegionsDrop = $('#spanRegionsDrop');

        var isOpen = spanRegionsDrop.hasClass('b-txtdrop-open');

        divMenu.hide();
        spanRegionsDrop.removeClass('b-txtdrop-open');

        if (!isOpen) {
            spanRegionsDrop.addClass('b-txtdrop-open');

            var offset = spanRegionsDrop.offset();
            //divMenu.css({ 'left': offset.left - $('#maincontent').offset().left + spanRegionsDrop.width() - 80 + 'px', 'top': '30px' });
            divMenu.css({ 'left': offset.left - $('#maincontent').offset().left + 25 + 'px', 'top': '30px' });
            $('ul[id*=ulRegions]').width(spanRegionsDrop.width() > 170 ? (spanRegionsDrop.width() + 20 + 'px') : '170px');
            divMenu.show();
        }

        spanRegionsDrop.mousedown(function() { return false; });
        divMenu.mousedown(function() { return false; });
    });

    $('ul[id*=ulRegions] li.cur').click(function() { return false; });

    $('ul[id*=ulRegions] span[id*=region]').click(function() {
        $('ul[id*=ulRegions] li.cur').removeClass('cur');
        $(this).parent().addClass('cur');
        $('#divRegionsList').hide();
        $('#spanRegionsDrop').removeClass('b-txtdrop-open');

        var regionId = this.id.substr(this.id.indexOf('_') + 1);
        $('#spanRegionsDrop').html('<span id="region_' + regionId + '">' + $(this).text() + '</span>');
        $("*[id $= hRegionId]").val(regionId);
    });
}

$(window).resize(function() {
    HideNavigation();
});

function HideNavigation() {
    $('div[id*=divDropNavB]').hide();
    $('span[id*=spanDropNav]').removeClass('darr-open');

    $('#divRegionsList').hide();
    $('#spanRegionsDrop').removeClass('b-txtdrop-open');
}
//End of Navigation (Green Line)

//----------------------------TRACKBAR-------------------------
String.prototype.replaceAll = function(search, replace) {
    return this.split(search).join(replace);
}
function addSpice(obj) {
    var currSign = $("input[id$=hCurrActiveSign]").val();
    obj.value = parseInt(obj.value.replaceAll(" ", ""));
    obj.value = DivideDigits(obj.value) + " " + currSign; ;
}
function delSpice(obj) {
    obj.value = parseInt(obj.value.replaceAll(" ", ""));
}
function DivideDigits(number) {
    var count = 0;
    for (var i = number.length - 1; i >= 0; i--) {
        count++; if (count % 3 == 0) number = number.substr(0, i) + ' ' + number.substr(i);
    } return trim(number);
}
function trim(string) { return string.replace(/(^\s+)|(\s+$)/g, ""); }
function setLeft(obj) {
    trackbar.getObject('one').updateLeftValue(obj.value.replaceAll(" ", ""));
    var reg = /[^0-9]/;
    if (obj.value.match(reg)) {
        obj.value = obj.value.toLowerCase().replaceAll(reg, "");
    }
}
function setRight(obj) {
    trackbar.getObject('one').updateRightValue(obj.value);
    var reg = /[^0-9]/;
    if (obj.value.match(reg)) {
        obj.value = obj.value.toLowerCase().replaceAll(reg, "");
    }
}
function setPrice(l, r, tmr) {
    $("input[id$=inputStartPrice]")[0].blur();
    $("input[id$=inputEndPrice]")[0].blur();
    var currSign = $("input[id$=hCurrActiveSign]").val();
    var objStartPrice = $("input[id$=inputStartPrice]")[0];
    objStartPrice.value = objStartPrice.value.replaceAll(" ", "");
    objStartPrice.value = DivideDigits(l.toString()) + " " + currSign;
    var objEndPrice = $("input[id$=inputEndPrice]")[0];
    objEndPrice.value = objEndPrice.value.replaceAll(" ", "");
    objEndPrice.value = DivideDigits(r.toString()) + " " + currSign;
    if (tmr) setTmr();
}

function ReInitPrice(setPostBackTimer) {
    //    var isIE = false;
    //    var agt = navigator.userAgent.toLowerCase();
    //    if (agt.indexOf("msie") != -1) {
    //        if (agt.substr(agt.indexOf("msie") + 5, 1) == '7') {
    //        isIE = true;
    //        //}
    //    }
    //    if (!isIE) {
    var leftL = parseInt($("*[id$=hOneLeftLimit]").val().replaceAll(" ", ""));
    var rightL = parseInt($("*[id$=hOneRightLimit]").val().replaceAll(" ", ""));
    var leftVal = parseInt($("*[id$=inputStartPrice]").val().replaceAll(" ", ""));
    var rightVal = parseInt($("*[id$=inputEndPrice]").val().replaceAll(" ", ""));
    var step = parseInt($("*[id$=hRoundUpTrackBar]").val().replaceAll(" ", ""));

    trackbar.getObject('one').init({
        onMove: function() {
            window.focus();
            setPrice(this.leftValue, this.rightValue, setPostBackTimer);
        },
        width: 225, // px
        leftLimit: leftL, // unit of value
        leftValue: leftVal, // unit of value
        rightLimit: rightL, // unit of value
        rightValue: rightVal, // unit of value
        roundUp: step,
        clearLimits: true,
        clearValues: true,
        hehe: ":-)"
    }, "track");
    //    }
    // TrackBarReInit(7,7777777);
}
//****driveVolume track
function InitVolume(setPostBackTimer) {
    var leftL = parseInt($("*[id$=hFromVolume]").val());
    var rightL = parseInt($("*[id$=hToVolume]").val());

    trackbar.getObject('two').init({
        onMove: function() {
            window.focus();
            setVolume(this.leftValue, this.rightValue, setPostBackTimer);
        },
        width: 225, // px
        leftLimit: leftL, // unit of value
        leftValue: leftL, // unit of value
        rightLimit: rightL, // unit of value
        rightValue: rightL, // unit of value
        roundUp: 1,
        clearLimits: true,
        clearValues: true,
        hehe: ":-)"
    }, "divDriveVolume");
    // TrackBarReInit(7,7777777);
}
function setLeftVolume(obj) {
    trackbar.getObject('two').updateLeftValue(obj.value.replaceAll(" ", ""));
    var reg = /[^0-9]/;
    if (obj.value.match(reg)) {
        obj.value = obj.value.toLowerCase().replaceAll(reg, "");
    }
}
function setRightVolume(obj) {
    trackbar.getObject('two').updateRightValue(obj.value);
    var reg = /[^0-9]/;
    if (obj.value.match(reg)) {
        obj.value = obj.value.toLowerCase().replaceAll(reg, "");
    }
}
function setVolume(l, r, tmr) {
    $("input[id$=txtFromVolume]")[0].value = l;
    $("input[id$=txtToVolume]")[0].value = r;
    if (tmr) setTmr();
}


//Popups
function ShowVipPopup() {
    $("div.l-tint").show();
    $("#divPopup").html('<h2>VIP объявления</h2><p>Чтобы сделать ваше объявление VIP объявлением отправьте SMS с&nbsp;сообщением</p><p class="sms">L #####</p><p>на короткий номер <strong class="sms-num">9993</strong>,<br />где #####&nbsp;&mdash; номер вашего объявления.</p><div class="hint"><p>Стоимость услуги 9900&nbsp;рублей для абонентов МТС, velcom и life:) без учета налогов.</p><!--<p class="link"><a href="#" target="_blank" class="link-info">Информация об услуге</a></p>--></div><p class="bt-wrap"><a onclick="ClosePopup()" class="bt-red"><span><span><span><span>Закрыть</span></span></span></span></a></p>');
    $("#divPopup").slideDown("normal");
}
function ClosePopup() {
    $("div.l-tint").hide();
    $("#divPopup").hide();
}
