var currentDictionary = englishDictionary;

if ($) {
    $(document).ready(function() {

        var language = GetCurrentLanguage();
        if (language == '/ru') {
            currentDictionary = russianDictionary;
        }
        else {
            currentDictionary = englishDictionary;
        }

        $("span.btn").attr("tabindex", "0");
        $("span.btn").live("blur", function() {
            $(this).removeClass("active");
        });
        $("span.btn").live("focus", function() {
            $(this).addClass("active");
        });

    });
    $(document).ajaxStart(function() { $('#header #logo a').addClass("gifLogo"); });
    $(document).ajaxStop(function() {
        $("span.btn").attr("tabindex", "0");
        $("#imageCode, #ImageCode").attr("autocomplete", "off");
        $("span.btn").keypress(function(e) { // onEnter under FF
            if (e.which == 13 && !$.browser.msie) {
                $(this).find("input").click();
            }
        });
        setTimeout(function() { $('#header #logo a').removeClass('gifLogo'); }, 500);
    });
    $(document).ajaxError(function(event, response, settings) {
        if (response.status == 433) window.location = window.location.pathname;
        else if (response.status == 400) window.location = '/Error/Http400';
        else if (response.status == 403) window.location = '/Error/Http403';
        else if (response.status == 404) window.location = '/Error/Http404';
        else if (response.status == 500) window.location = '/Error/Http500';
        else {
            $('#serverMessage').html('<span class="error-message">The web server was not able to process your request successfully. This might be related to resource contention issue.</span>');
            DisableButton($('#placeHolder input[type=submit]'), false);
        }
    });
}
$("a[rel]").attr("target", "_blank");
$("a[rel]").removeAttr("rel");
$("#imageCode, #ImageCode").attr("autocomplete", "off");

$("span.btn").keypress(function(e) { // onEnter under FF
    if (e.which == 13 && !$.browser.msie) {
        $(this).find("input").click();
    }
});



// ----- Applies Google Analytics -----
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
try { var pageTracker = _gat._getTracker("UA-11070560-1"); pageTracker._trackPageview(); } catch (err) { }

function DisableButton(button, disabled) {
    if (button.parentNode == undefined) { button = button[0]; }
    var parent = button.parentNode;
    if (disabled) { button.disabled = true; if (parent.className.indexOf(' disabled') < 0) { parent.className = parent.className.concat(' disabled'); } }
    else { button.disabled = false; parent.className = parent.className.replace('disabled', ''); }
}

// ----- Custom Select -----
var customSelectFolder = {
    list: {},
    add: function(name, obj) {
        customSelectFolder.list[name] = new CustomSelect(obj.el, obj.value);
    }
}
function CustomSelect(el, values) {
    this.init = false;
    this.onChange = function() { }
    this.selectedIndex = false;
    this.element = el || document.getElementById('test');
    this.values = values;

    this.setDisabled = function() {
        _this.values.disabled = true;
        $(_this.element).find('*').css('color', '#c0c0c0').end().find('input:first').attr("disabled", "disabled");

    };
    this.setEnabled = function() {
        _this.values.disabled = false;
        $(_this.element).find('*').css('color', '').end().find('input:first').removeAttr("disabled", "disabled");
    };

    this.show = function(e) {
        if (_this.values.disabled == true) return false;
        if (customSelectFolder.activ && customSelectFolder.activ != _this) customSelectFolder.activ.hide();

        customSelectFolder.activ = _this;

        e.stopPropagation()

        if ($(_this.element).find('div.ul:first').css('display') == 'none') {
            $(_this.element).find('div.ul').css({
                display: 'block'
            });
            $(_this.element).css({
                zIndex: '99'
            });

            $(_this.element).parent().css({ zIndex: '99' });
            $(document).one('mousedown', _this.hide)
        } else
            _this.hide();
    };
    this.hide = function() {
        customSelectFolder.activ = false;

        $(_this.element)
			.css({ zIndex: '' })
			.find('div.ul')
			.css({ display: 'none' });

        $(_this.element).parent().css({ zIndex: '' });
    }

    this.setSelected = function(e) {
        e = e || window.event;
        var targ = targ || e.srcElement || e.target;
        _this.selected.className = '';
        _this.selected = targ;
        _this.selected.className = 'activ';
    }

    this.setValue = function(e, targ, propagation) {
        e = e || window.event;

        var targ = targ || e.srcElement || e.target;

        _this.selected.className = '';
        _this.selected = targ;
        _this.selected.className = 'activ';

        $(_this.element).find("span").html(targ.innerHTML);

        if (targ.attributes.getNamedItem('selectvalue') && (targ.attributes.getNamedItem('selectvalue').specified)) {
            $(_this.element).find("input").val(targ.getAttribute('selectvalue'));
        } else {
            $(_this.element).find("input").removeAttr('value');
        }

        _this.selectedIndex = $(_this.element).find('li').length - $(targ).nextAll().length - 1;

        $(_this.element).find('input:first').focus();

        if (!e || !e.keyCode || e.keyCode == 13 || e.keyCode == 27)
            _this.hide();

        if (_this.init && propagation != 'stop') {
            _this.onChange();
        }
    }

    var _this = this;
    var el = $('<div class="select"><div class="first">&nbsp;</div><span></span><input type="text"><div style="display:none" class="ul"><div class="ul_t"></div><div class="ul_l"></div><div class="ul_b"></div><div class="ul_r"></div><div class="ul_t_l"></div><div class="ul_t_r"></div><div class="ul_b_l"></div><div class="ul_b_r"></div><ul></ul></div><div class="pointer">&nbsp;</div></div>');

    el.find('input:first').attr('name', $(this.element).attr('name'));
    el.find('input:first').attr('id', $(this.element).attr('id'));

    $(this.element).replaceWith(el)

    this.element = el[0];

    for (var tmp in this.values) {
        // Before FIX: if (tmp=='disabled' && this.values.disabled=='disabled'){ this.setDisabled(); continue;};
        if (tmp == 'disabled' && this.values.disabled) { this.setDisabled(); continue; };

        if (this.values[tmp].value.length > 0) {
            $(this.element).find('ul').append("<li selectvalue='" + (this.values[tmp].value) + "'>" + this.values[tmp].label + "</li>");
        }
        else {
            $(this.element).find('ul').append("<li>" + this.values[tmp].label + "</li>");
        }

        if (this.values[tmp].selected) this.selected = $(this.element).find('li:last')[0];
    }

    this.selected = this.selected || $(this.element).find('li:first')[0];
    this.setValue(false, this.selected);

    $(this.element, this.element.lastChild).bind('mousedown', this.show);
    $(this.element).find('li').each(function() {
        $(this)
			.bind('mousemove', _this.setSelected)
			.bind('mouseup', _this.setValue)
			.bind('mousedown', function(e) { e.stopPropagation(); })
    })

    this.options = $(this.element).find('li').get();
    this.init = true;
}
function CustomSelectStart() {
    $('.select').remove();
    var selectList = document.getElementsByTagName('SELECT');

    while (selectList[0]) {
        var value = {};
        value.value = {};
        if (selectList[0].getAttribute('disabled')) value.value.disabled = true;
        for (var i = 0; i < selectList[0].childNodes.length; i++) {
            if (selectList[0].childNodes[i].nodeType != 3) {
                value.el = selectList[0];
                value.value[i] = {};
                value.value[i].value = selectList[0].childNodes[i].getAttribute('value');
                value.value[i].label = selectList[0].childNodes[i].innerHTML;
                if (selectList[0].childNodes[i].getAttribute('selected')) value.value[i].selected = true;
            }
        }
        window.customSelectFolder.add(selectList[0].getAttribute('ID'), value);
    }


    function validateDepend(i) {
        var root = window.customSelectFolder.list[dependentSelect[i].rName];
        var dep = window.customSelectFolder.list[dependentSelect[i].dName];

        if (root != null)
            root.onChange = function() {
                if ((dependentSelect[i].dependent[root.selectedIndex] + 1)
        && (dep.selectedIndex != dependentSelect[i].dependent[root.selectedIndex])) {
                    dep.setValue(false, dep.options[dependentSelect[i].dependent[root.selectedIndex]], 'stop');
                };
                if (dependentSelect[i].responseFunc != null)
                    dependentSelect[i].responseFunc();
            }
    }

    if (window.dependentSelect) for (var i = 0; i < dependentSelect.length; i++) validateDepend(i);
}

function NavigateAccountSidebar(requestPath) {
    $('#sidebar_menu a[href=' + GetCurrentLanguage() + requestPath + ']').addClass('boldA');
    $('#sidebar_menu a').live('click', function(event) {
        $('#sidebar_menu a').removeClass('boldA'); $(this).addClass('boldA');
        var form = $('#mainForm');
        $.post(this.href, form.serialize(), function(data) { $('#placeHolder').html(data); });
        event.preventDefault();
    });
}

function SubmitForm(container, formname) {
    if (!container) container = '#placeHolder';
    if (!formname) formname = '#mainForm';

    $(container + ' input[type=submit]').live('click', function(event) {
        //    $(container + ' input[type=submit].attr("disabled")').live('click', function(event) {
        if ($(container + ' input[type=submit]').attr("disabled"))
            return false;
        event.preventDefault();

        var form = $(formname);
        var data = null;
        if (this.name) {
            data = form.serializeArray();
            data.push({ name: this.name, value: this.value });
            data = jQuery.param(data);
        }
        else
            data = form.serialize();
        $.post(form.attr('action'), data, function(data, textStatus) {
            if (textStatus == "success") {
                $(container).html(data);
                if (this.url.indexOf('DeleteMessages') > 0) {
                    $.get('/Messages/RefreshMenu/0', function(data) { $('#inboxMessagesMenuItem').html(data); });
                    $.get('/Messages/MyEzMenu/0', function(data) { $('#my_ez_menu>div').html(data); });
                }
                FadeOutStatusMessag();
            }
        });
        event.preventDefault();
    });
}

function ManageNotificationCheckBoxes() {
    $('input[type=checkbox]').click(function(event) {
        var fieldsetId = this.parentNode.parentNode.id;
        if (this.id == 'chbCheckAll') {
            //Check Uncheck All In Group
            $('#' + fieldsetId + ' input[id=chBox]').attr('checked', this.checked);
            if (this.checked)
                $('#' + fieldsetId + ' label')[0].innerHTML = currentDictionary.UncheckAll;
            else
                $('#' + fieldsetId + ' label')[0].innerHTML = currentDictionary.CheckAll;
        }

        if (this.id == 'chBox') {
            //see if each in group has all selected
            if ($('#' + fieldsetId).find('input[id=chBox]:checked').size() == $('#' + fieldsetId).find('input[id=chBox]').size()) {
                if ($('#' + fieldsetId + ' input[id=chbCheckAll]')[0] != undefined) {
                    $('#' + fieldsetId + ' input[id=chbCheckAll]')[0].checked = true;
                    $('#' + fieldsetId + ' label')[0].innerHTML = currentDictionary.UncheckAll;
                }
            } else {
                if ($('#' + fieldsetId + ' input[id=chbCheckAll]')[0] != undefined) {
                    $('#' + fieldsetId + ' input[id=chbCheckAll]')[0].checked = false;
                    $('#' + fieldsetId + ' label')[0].innerHTML = 'Check all';
                }
            }
        }
    });

    if ($('#OfferGroup input[id=chBox]:checked').size() == $('#OfferGroup input[id=chBox]').size())
        if ($('#OfferGroup')[0] != undefined) {
        $('#OfferGroup input[id=chbCheckAll]')[0].checked = true;
        $('#OfferGroup label')[0].innerHTML = currentDictionary.UncheckAll;
    }
    if ($('#BidGroup input[id=chBox]:checked').size() == $('#BidGroup input[id=chBox]').size())
        if ($('#OfferGroup')[0] != undefined) {
        $('#BidGroup input[id=chbCheckAll]')[0].checked = true;
        $('#BidGroup label')[0].innerHTML = currentDictionary.UncheckAll;
    }
    if ($('#ExchangeGroup input[id=chBox]:checked').size() == $('#ExchangeGroup input[id=chBox]').size())
        if ($('#OfferGroup')[0] != undefined) {
        $('#ExchangeGroup input[id=chbCheckAll]')[0].checked = true;
        $('#ExchangeGroup label')[0].innerHTML = currentDictionary.UncheckAll;
    }
    if ($('#AccountGroup input[id=chBox]:checked').size() == $('#AccountGroup input[id=chBox]').size())
        if ($('#OfferGroup')[0] != undefined) {
        $('#AccountGroup input[id=chbCheckAll]')[0].checked = true;
        $('#AccountGroup label')[0].innerHTML = currentDictionary.UncheckAll;
    }
    if ($('#UserInfoGroup input[id=chBox]:checked').size() == $('#UserInfoGroup input[id=chBox]').size())
        if ($('#OfferGroup')[0] != undefined) {
        $('#UserInfoGroup input[id=chbCheckAll]')[0].checked = true;
        $('#UserInfoGroup label')[0].innerHTML = currentDictionary.UncheckAll;
    }
}

function ActivityScripts(settings) {
    var urlAction;
    var lastSelectedA;
    customSelectFolder.list['DateRangeSelector'].setValue(false, customSelectFolder.list['DateRangeSelector'].options[1], 'stop');

    $('#sidebar_menu a').live('click', function(event) {
        $('#sidebar_menu a').removeClass('boldA'); $(this).addClass('boldA');
        lastSelectedA = this;
        urlAction = this.href;
        if (urlAction.indexOf('Locked') < 0) {
            $('#sidebar_menu_filter').show();
        }
        else {
            $('#sidebar_menu_filter').hide();
        }
        var selected = $('#DateRangeSelector').val();
        $.post(urlAction + '&DateRange=' + selected, function(data) { $('#placeHolder').html(data); });
        event.preventDefault();
    });

    customSelectFolder.list['DateRangeSelector'].onChange = function() {
        this.disabled = true;
        var selected = $('#DateRangeSelector').val();
        if (urlAction == undefined) {
            urlAction = document.location.pathname;
        }

        var language = GetCurrentLanguage();

        if (urlAction.indexOf('MyExchanges') > 0) {
            urlAction = language + '/MyExchanges';
        } else if (urlAction.indexOf('MyOffers') > 0) {
            urlAction = language + '/MyOffers';
        } else if (urlAction.indexOf('MyBids') > 0) {
            urlAction = language + '/MyBids';
        }

        $.get(language + '/Activity/RefreshMenu?DateRange=' + selected, function(data) { $('#ActivityPanel').html(data); });

        if ($('#ItemsStatus').val() == undefined)
            $.get(urlAction + '?DateRange=' + selected, function(data) { $('#placeHolder').html(data); });
        else
            $.get(urlAction + '?DateRange=' + selected + '&Status=' + $('#ItemsStatus').val(), selected, function(data) { $('#placeHolder').html(data); });

        this.disabled = false;
    };

    $(document).ajaxStop(function() {
        if (lastSelectedA != undefined) $('#sidebar_menu a[id=' + lastSelectedA.id + ']').addClass("boldA");
    });
}

function MessagesScripts(settings) {
    customSelectFolder.list['DateRangeSelector'].setValue(false, customSelectFolder.list['DateRangeSelector'].options[1], 'stop');
    //hilight sidebar menu item
    $('#sidebar_menu #announcementsLink').addClass('boldA');
    $('#sidebar_menu a').each(function(event) {
        if (settings.ajaxSettings.url == this.href) {
            $('#sidebar_menu #announcementsLink').removeClass('boldA');
            $(this).addClass('boldA');
        }
    });

    var urlAction;
    var dateRangeForm = $('#DateRangeForm');
    if ($('#BoxType').val() == 'InBox' || $('#BoxType').val() == 'SentBox' || $('#BoxType').val() == 'DeletedBox') {
        dateRangeForm.show();
    }
    else {
        dateRangeForm.hide();
    }

    //navigate messages sidebar menu
    $('#sidebar_menu a').live('click', function(event) {
        $('#sidebar_menu a').removeClass('boldA'); $(this).addClass('boldA');
        urlAction = this.href;
        if (this.href.indexOf('NewMessage') < 0 && this.href.indexOf('NotificationMessages') < 0) {
            if (this.href.indexOf('AnnouncementsBox') < 0) {
                dateRangeForm.show();
            }
            else {
                dateRangeForm.hide();
                customSelectFolder.list['DateRangeSelector'].setValue(false, customSelectFolder.list['DateRangeSelector'].options[1], 'stop');
            }
            $.get(urlAction + '?DateRange=' + $('#DateRangeSelector').val(), null, function(data) { $('#placeHolder').html(data); });
            if (this.href.indexOf('InBox') > 0) $.get(GetCurrentLanguage() + '/Messages/RefreshMenu/0', function(data) { $('#inboxMessagesMenuItem').html(data); $('#sm_inbox').addClass('boldA'); });
        }
        else {
            dateRangeForm.hide();
            $.get(urlAction, null, function(data) { $('#placeHolder').html(data); });
        }
        event.preventDefault();
    });

    $('#chbCheckAll').live('click', function() {
        $('input[type=checkbox]').attr('checked', this.checked);
        DisableButton($('input[type=submit]'), !this.checked);
    });
    $("input[name='MessageIds']").live('click', function() {
        //see if each in group has all selected
        if ($('#placeHolder').find('input[id=chbDelete]:checked').size() == $('#placeHolder').find('input[id=chbDelete]').size())
            $('input[id=chbCheckAll]')[0].checked = true;
        else
            $('input[id=chbCheckAll]')[0].checked = false;

        DisableButton($('input[type=submit]'), $("input[name='MessageIds']:checked").length == 0);
    });

    customSelectFolder.list['DateRangeSelector'].onChange = function() {
        var selected = $('#DateRangeSelector').val();
        if (urlAction == undefined) urlAction = settings.ajaxSettings.url;

        $.get(urlAction + '?DateRange=' + selected, function(data) { $('#placeHolder').html(data); });
    };
}

// Added for navigation from Site Map
function NewMessageScripts() {
    $('#sidebar_menu a').live('click', function(event) {
        $('#sidebar_menu a').removeClass('boldA'); 
        $(this).addClass('boldA');
        if (this.href.indexOf('NewMessage') > 0 || this.href.indexOf('NotificationMessages') > 0) {
            urlAction = this.href;
            $.get(urlAction, null, function(data) { $('#placeHolder').html(data); });
            event.preventDefault();
        }
    });
}

function HighlightAnnouncement() {
    $('#sidebar_menu a[href=/Messages/AnnouncementsBox]').addClass('boldA');
}

function MessageDetails(box) {
    function RefreshHistory() {
        $.get(GetCurrentLanguage() + '/Message/MessageHistory/' + $('#MessageId').val() + '?DateRange=' + $('#DateRangeSelector').val(), function(data, textStatus) {
            if (textStatus == "success") {
                $('#placeHolder').html(data);
                $('#showHideHistoryLink')[0].innerHTML = currentDictionary.HideMessageHistory;
                $('#placeHolder').slideDown();
            }
        });
    }

    $('#DateRangeForm').hide();

    customSelectFolder.list['DateRangeSelector'].setValue(false, customSelectFolder.list['DateRangeSelector'].options[1], 'stop');
    $('#sidebar_menu a[href=/Messages/' + box + ']').addClass('boldA');
    $('#showHideHistoryLink').live('click', function(event) {
        if (this.innerHTML == currentDictionary.ShowMessageHistory) {
            $('#DateRangeForm').slideDown();
            RefreshHistory()
            event.preventDefault();
        } else {
            customSelectFolder.list['DateRangeSelector'].setValue(false, customSelectFolder.list['DateRangeSelector'].options[1], 'stop');
            $('#placeHolder').slideUp();
            $('#DateRangeForm').slideUp();
            this.innerHTML = currentDictionary.ShowMessageHistory;
        }
    });

    if (box == 'InBox') {
        FadeOutStatusMessag();
    };

    customSelectFolder.list['DateRangeSelector'].onChange = function() {
        RefreshHistory()
    };
}

function LinkClick(container, link) {
    $.get(link.href, function(data) { $(container).html(data); });
};

function NavigatePaging() {
    $('#placeHolder>.group li a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#placeHolder', this);
    });
    $('#exchangePlaceHolder li a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#exchangePlaceHolder', this);
    });
    $('#offersPlaceHolder li a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#offersPlaceHolder', this);
    });
    $('#bidsPlaceHolder li a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#bidsPlaceHolder', this);
    });
}
function DefaultPaging() {
    $("#placeHolder div.pg li a").live("click", function(event) {
        event.preventDefault();
        LinkClick('#placeHolder', this);
    });
}
function SupportPaging(containerId) {
    $('#' + containerId + ' li a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#' + containerId, this);
    });
}

// --------- Text validation --------
function Contains(list, value) {
    for (var i = 0; i < list.length; i++) {
        if (list[i] == value) { return true; }
    }
    return false;
}
function IsEngAlpha(charCode) {
    return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122);
}
function IsDigit(charCode) {
    return (charCode >= 48 && charCode <= 57);
}
function ValidateKey(e, test) {
    if (e.ctrlKey || e.altKey || Contains([8, 13, 9], e.keyCode)) {
        return true;
    }
    return e.which == 0 || test(e.which);
}

function ValidateAmount(e) {
    return ValidateKey(e, function(charCode) { return IsDigit(charCode) || charCode == 46 || charCode == 44; });
}

function ValidateIP(e) {
    return ValidateKey(e, function(charCode) { return IsDigit(charCode) || charCode == 46; });
}

function ValidateLiberty(e) {
    return ValidateKey(e, function(charCode) { return IsDigit(charCode) || Contains([117, 85, 120, 88, 109, 77], charCode); });
}

function ValidateCountry(e) {
    return ValidateKey(e, function(charCode) { return IsEngAlpha(charCode) || Contains([32, 40, 41, 46, 39, 45], charCode); });
}

function ValidateEMail(e) {
    return ValidateKey(e, function(charCode) { return IsEngAlpha(charCode) || IsDigit(charCode) || Contains([45, 95, 64, 46], charCode); });
}

function ValidateAccount(e) {
    return ValidateKey(e, function(charCode) { return IsEngAlpha(charCode) || IsDigit(charCode); });
}

function ValidateNumber(e) {
    return ValidateKey(e, function(charCode) { return IsDigit(charCode); });
}

function ValidateBatchNumber(e) {
    return ValidateKey(e, function(charCode) { return IsEngAlpha(charCode) || IsDigit(charCode); });
}

function ValidateComment(e) {
    return ValidateKey(e, function(charCode) { return !Contains([60, 62, 123, 125, 91, 93], charCode); });
}

function ValidateDate(e) {
    return ValidateKey(e, function(charCode) { return IsDigit(charCode) || charCode == 47; });
}

function KeyPressResult(e, func) {
    if (!func(e)) { e.preventDefault(); }
}

function ValidateInputText() {
    $("input.validamount").live("keypress", function(e) {
        KeyPressResult(e, ValidateAmount);
    });
    $("input.validip").live("keypress", function(e) {
        KeyPressResult(e, ValidateIP);
    });
    $("input.validliberty").live("keypress", function(e) {
        KeyPressResult(e, ValidateLiberty);
    });
    $("input.validcountry").live("keypress", function(e) {
        KeyPressResult(e, ValidateCountry);
    });
    $("input.validemail").live("keypress", function(e) {
        KeyPressResult(e, ValidateEMail);
    });
    $("input.validaccount").live("keypress", function(e) {
        KeyPressResult(e, ValidateAccount);
    });
    $("input.validnumber").live("keypress", function(e) {
        KeyPressResult(e, ValidateNumber);
    });
    $("input.validbatch").live("keypress", function(e) {
        KeyPressResult(e, ValidateBatchNumber);
    });
    $("textarea.validcomment").live("keypress", function(e) {
        KeyPressResult(e, ValidateComment);
    });
    $("input.validdate").live("keypress", function(e) {
        KeyPressResult(e, ValidateDate);
    });
}
//--------
function MakeSearch(button) {
    if (button) DisableButton(button, true);

    var form = $('#searchForm');
    var url = form.attr('action');
    $.get(url, form.serialize(), function(data) {
        if (button) DisableButton(button, false);
        $('#placeHolder').html(data);
    });
}
function OffersSearchPanel() {
    $('input[type=submit]').live('click', function(event) {
        MakeSearch(this);
        event.preventDefault();
    });

    $('th a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#placeHolder', this);
    });

    if (!window.dependentSelect) window.dependentSelect = [];
    window.dependentSelect.push({ rName: 'SellerPaymentSystem', dName: 'BuyerPaymentSystem', dependent: SellerPaymentChanged, responseFunc: SellerPaymentChanged });
    window.dependentSelect.push({ rName: 'BuyerPaymentSystem', dName: 'SellerPaymentSystem', dependent: BuyerPaymentChanged, responseFunc: BuyerPaymentChanged });
    window.dependentSelect.push({ rName: 'Status', dName: 'DaysFilter', dependent: { 0: 1, 1: 1, 2: 1 }, responseFunc: function() {
        var selected = $('#Status').val();
        if (selected == 1) // Open
        {
            $('#OfferAgeContainer').hide();
        }
        else {
            $('#OfferAgeContainer').show();
        }
    }
    });
}

function SellerPaymentChanged() {
    PaymentChanged(customSelectFolder.list['SellerPaymentSystem'], customSelectFolder.list['BuyerPaymentSystem']);
}
function BuyerPaymentChanged() {
    PaymentChanged(customSelectFolder.list['BuyerPaymentSystem'], customSelectFolder.list['SellerPaymentSystem']);
}
function PaymentChanged(source, target) {
    if (source.selectedIndex == 0) {
        if (target.selectedIndex <= 2) {
            if (target.selectedIndex == 0)
                target.setValue(false, target.options[2], 'stop');
            else
                target.setValue(false, target.options[target.selectedIndex], 'stop');
        } else {
            target.setValue(false, target.options[2], 'stop');
        }
        $('#StrategyContainer').hide();
    } else if (IsSourceInRelationWithTarget(source.selectedIndex, target.selectedIndex)) {
        if (source.selectedIndex == 7 | source.selectedIndex == 12 | source.selectedIndex == 14)
            target.setValue(false, target.options[1], 'stop');
        else if (source.selectedIndex == 8 | source.selectedIndex == 13 | source.selectedIndex == 15)
            target.setValue(false, target.options[2], 'stop');
        else
            if (!IsSourceInRelationWithTarget(source.selectedIndex, target.selectedIndex))
                target.setValue(false, target.options[2], 'stop');
        $('#StrategyContainer').show();
    } else if (!IsSourceInRelationWithTarget(source.selectedIndex, target.selectedIndex)) {
        if (source.selectedIndex <= 2) {
            target.setValue(false, target.options[0], 'stop');
            $('#StrategyContainer').hide();
        } else {
            if (source.selectedIndex == 7 | source.selectedIndex == 12 | source.selectedIndex == 14)
                target.setValue(false, target.options[1], 'stop');
            else if (source.selectedIndex == 8 | source.selectedIndex == 13 | source.selectedIndex == 15)
                target.setValue(false, target.options[2], 'stop');
            else
                if (!IsSourceInRelationWithTarget(source.selectedIndex, target.selectedIndex))
                target.setValue(false, target.options[2], 'stop');
            $('#StrategyContainer').show();
        }
    } else {
        $('#StrategyContainer').hide();
    }
}
function IsSourceInRelationWithTarget(sourceIndex, targetIndex) {
    if ((sourceIndex == 1 | sourceIndex == 2) & targetIndex >= 3) return true;
    if ((targetIndex == 1 | targetIndex == 2) & sourceIndex >= 3) return true;
}

function ManagePartnerExchangeComments() {
    $('#placeHolder h3 a').live('click', function(event) {
        this.disabled = true;
        $.get($('#selectLink').attr('href'), function(data, textStatus) { $('#placeHolder').html(data); });
        event.preventDefault();
    });

    $('#placeHolder li a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#placeHolder', this);
    });

    $('#canceledExchangesPlaceHolder h3 a').live('click', function(event) {
        this.disabled = true;
        $.get($('#selectCanceledLink').attr('href'), function(data, textStatus) { $('#canceledExchangesPlaceHolder').html(data); });
        event.preventDefault();
    });

    $('#canceledExchangesPlaceHolder li a').live('click', function(event) {
        event.preventDefault();
        LinkClick('#canceledExchangesPlaceHolder', this);
    });
}

function ExchangeScripts() {
    $('.collapse').live('click', function(event) {
        this.className = 'expand';
        var step = this.parentNode.parentNode.parentNode;
        var fieldset = $(step).find('fieldset');
        fieldset.hide();
    });
    $('.expand').live('click', function(event) {
        this.className = 'collapse';
        var step = this.parentNode.parentNode.parentNode;
        var fieldset = $(step).find('fieldset');
        fieldset.show();
    });
    $('#ConfirmCheck').live('click', function(event) {
        if ($('#ConfirmCheck').is(':checked')) DisableButton($('input[value=Confirm]'), false);
        else DisableButton($('input[value=Confirm]'), true);
    });
}

function RestorePasswordScripts() {
    $('#restore #tabLink').live('click', function(event) {
        $.get(this.href, function(data) { $('#placeHolder').html(data); });
        event.preventDefault();
    });
    $('#placeHolder input[name=actionName]').live('click', function(event) {
        DisableButton(this, true);
        var form = $("#mainForm");
        $.post(form.attr('action'), form.serialize(), function(data) { $('#placeHolder').html(data); });
        event.preventDefault();
    });
    $('input[name=enterPassword]').live('click', function(event) {
        PreventButtonDoubleClick(this);
    });
}
function OfferDetailsScripts(container) {
    $("a.btn").live("click", function(e) {
        LinkClick(container, this);
        e.preventDefault();
    });
}

function NewOfferScripts() {
    $('input[name=PaymentSystemId]').live('click', function(e) {
        ChangePayment(this.value);
    });
    $('input[name=Role]').live('click', function(e) {
        UpdateTitle(this.value);
        ChangePayment($('input[name=PaymentSystemId]:radio:checked').val());
    });
    $('input[name=CurrencyId]').live('click', function(e) {
        ChangePaymentsList(this.value);
    });
    Start();

    $(document).ajaxSuccess(function(evt, response, settings) { Start() });
}
function Start() {
    if ($('input[name=step][value=Step1]').length > 0) {
        UpdateWarning($('input[name=PaymentSystemId]:radio:checked').val());
        UpdateTitle($('input[name=Role]:radio:checked').val());
    }
}

function RegistrationScripts() {
//Do not delete
//    $('#ConfirmAgreement').live('click', function(event)
//    {
//        if ($('#ConfirmAgreement').is(':checked')) DisableButton($('input[value=Register]'), false);
//        else DisableButton($('input[value=Register]'), true);
//    });
    CheckAvailability();
}

function UpdateWarning(value) {
    if (warnings[value] != null) {
        $('#paymentWarning').html('<span class="red">*</span>' + warnings[value]);
    }
    else {
        $('#paymentWarning').html('');
    }
};
function UpdateTitle(buy) {
    $('#result').text(buy == 'Buyer' ? currentDictionary.IWillSend : currentDictionary.IWantToReceive);
}
function ChangePayment(value) {
    UpdateWarning(value);
    $('#verifiedWarning').hide();
    if ($('input[type=submit]')[0].disabled) DisableButton($("input[type=submit]")[0], false);
};
function ChangePaymentsList(value) {
    if (value == 1) {
        $('#want_receive_usd').show();
        $('#want_receive_eur').hide();
        $('input[name=PaymentSystemId]')[8].checked = true;
        ChangePayment(17); // Western Union Usd
    }
    else {
        $('#want_receive_usd').hide();
        $('#want_receive_eur').show();
        $('input[name=PaymentSystemId]')[11].checked = true;
        ChangePayment(25); //Western Union Eur
    }
};


function NavigateTabs() {
    $('#tabs h3').click(function(e) {
        $('#tabs .active').removeClass('active');
        $(this).parent().addClass('active');
    });
}

function PreventButtonDoubleClick(button) {
    setTimeout(function() {
        DisableButton(button, true);
    }, 0);
}
function PreventDoubleClicks() {
    $("a.btn").live("click", function(e) {
        if ($(this).is("disabled")) {
            e.preventDefault();
            return false;
        }
        _this = this;
        setTimeout(function() {
            $(_this).addClass("disabled");
            $(_this).removeAttr("href");
        }, 0);
    });
    $('input[type=submit]').click(function(event) {
        PreventButtonDoubleClick(this);
    });
}

function CheckAvailability() {
    $('#DisplayName').bind('blur', function(event) {
        var form = $('#mainForm');
        $.post('/Registration/NicknameAvailability', form.serialize(), function(data) { $('#placeHolder').html(data); CheckAvailability(); $('#Password').focus(); $('#Password').focus(); });

    });
    
    
}

function GenerateCaptcha(controller) {
    $('#generateCaptcha').live('click', function(event) {
        event.preventDefault();
        var form = $('#mainForm');
        $.post('/' + controller + '/GenerateCaptcha', form.serialize(), function(data) { $('#captchaPlaceHolder').html(data); });
    });
}

function GenerateNewMessageCaptcha() {
    $('#generateNewMessageCaptcha').live('click', function(event) {
        event.preventDefault();
        var form = $('#mainForm');
        $.post('/Message/GenerateNewMessageCaptcha', form.serialize(), function(data) { $('#captchaPlaceHolder').html(data); });
    });
}

function GenerateQuickReplyCaptcha() {
    $('#generateQuickReplyCaptcha').live('click', function(event) {
        event.preventDefault();
        var form = $('#mainForm');
        $.post('/Message/GenerateQuickReplyCaptcha', form.serialize(), function(data) { $('#captchaPlaceHolder').html(data); });
    });
}

function GenerateRequestCodeCaptcha() {
    $('#generateRequestCodeCaptcha').live('click', function(event) {
        event.preventDefault();
        var form = $('#mainForm');
        $.post('/RestorePassword/RequestCodeGenerateCaptcha', form.serialize(), function(data) { $('#placeHolder').html(data); });
    });
}

function GenerateEnterCodeCaptcha() {
    $('#generateEnterCodeCaptcha').live('click', function(event) {
        event.preventDefault();
        var form = $('#mainForm');
        $.post('/RestorePassword/EnterCodeGenerateCaptcha', form.serialize(), function(data) { $('#placeHolder').html(data); });
    });
}

function SupportSubmitForm() {
    $('#placeHolder input[type=submit]').live('click', function(event) {
        if ($('#placeHolder input[type=submit]').attr("disabled")) return false;
        event.preventDefault();

        var form = $('#mainForm');
        var data = null;
        if (this.name) {
            data = form.serializeArray();
            data.push({ name: this.name, value: this.value });
            data = jQuery.param(data);
        }
        else
            data = form.serialize();
        $.post(form.attr('action'), data, function(data, textStatus) {
            if (textStatus == "success") {
                $('#placeHolder').html(data);
                CustomSelectStart();
                $.get(GetCurrentLanguage() + '/Support/Tickets/GetMyTicketsMenuHolder', function(data) {
                    $('#myTicketsMenuHolder').html(data);
                    if (form.attr('action').indexOf('/Support/NewTicket') > 0) SupportHighLightSidebarMenuItem(undefined, 'newTicketLink');
                    if (form.attr('action').indexOf('/Support/Ticket/Index/') > 0) SupportHighLightSidebarMenuItem(undefined, 'viewMyTickets');
                });
                FadeOutStatusMessag();
            }
        });
        event.preventDefault();
    });
}

function PostReply(container, formname) {
    $(container + ' input[type=submit]').live('click', function(event) {
        if ($(container + ' input[type=submit]').attr("disabled")) return false;
        event.preventDefault();

        var form = $(formname);
        var data = null;
        if (this.name) {
            data = form.serializeArray();
            data.push({ name: this.name, value: this.value });
            data = jQuery.param(data);
        }
        else
            data = form.serialize();
        $.post(form.attr('action'), data, function(data, textStatus) {
            if (textStatus == "success") {
                $(container).html(data);
                if (!$('.field-validation-error').is(':visible')) $(container + ' textarea').text('');
                FadeOutStatusMessag('#status-message-reply-post');
            }
        });
        event.preventDefault();
    });
}

function SupportHighLightSidebarMenuItem(menuItemHref, menuItemId) {
    if (menuItemHref) $('#sidebar_menu a[href=' + GetCurrentLanguage() + menuItemHref + ']').addClass('boldA');
    if (menuItemId) $('#sidebar_menu #' + menuItemId).addClass('boldA');
}

function GetCurrentLanguage() {
    var lang = document.location.pathname.substring(0, 3);
    if (lang != '/ru' && lang != '/en')
        lang = '/en'
    return lang;
}

function FadeOutStatusMessag(statusMessageId) {
    if (!statusMessageId) statusMessageId = '#status-message';
    if ($(statusMessageId).is(':visible')) {
        setTimeout(function() {
            $(statusMessageId).fadeOut(1700);
        }, 3000);
    }
}