/*
 * Events called on every page load on vanilla and PSUSA2.
 */
var loader = function (target, do_not_wrap_it) {
    if (do_not_wrap_it) {
        var wrapper = target.addClass('loader-parent').css('position','relative');
    } else {
        var wrapper = target.parent();
        if (!wrapper.hasClass('loader-parent')) wrapper = target.wrap(document.createElement("div")).parent().addClass('loader-parent').css('position','relative');
    };

    return $('<div class="loading"></div>').css({
        width: '100%',
        height: '100%',
        position: 'absolute',
        left:0,
        top:0,
        opacity: 0.5
    }).appendTo(wrapper);
    },
    loader_done = function(l) {
    l.remove();
    };

(function($){
$.fn.inactivedefault = function(default_val) {
    return $(this).focus(function(f) { return function() {
                if (f.hasClass('inactive')) { f.removeClass("inactive").val("") }
            }; }($(this)))
            .blur(function(f) { return function() {
                if ((f.val()=='')||(f.val()==default_val)) { f.addClass("inactive").val(default_val) }
            }; }($(this))).blur();
    }
})(jQuery);

(function($){
$(document).ready(function(){
    var merchants = $('#searchSimpleForm input#merchants');
    var query = $('#searchSimpleForm input[name=query]');
    var where = $('#searchSimpleForm input[name=near_to]');

    $('#searchSimpleForm').submit(function() {
        if (merchants.attr('checked')) {
            merchants.attr('disabled','disabled');
            $(this).attr('action', '/profiles/');
        } else {
            $(this).attr('action', '/search/');
        }
        if (query.hasClass('inactive')) query.attr('disabled','disabled');
        if (where.hasClass('inactive')) where.attr('disabled','disabled');
        return true;
        })
    });
})(jQuery);


// copytext.js
function moveCopyTextToFooter() {
    head = document.getElementById("copy_top");
    foot = document.getElementById("copy_bottom");
    if(head && foot) {
        foot.innerHTML = head.innerHTML;
        head.style.display = "none";
    }
}

function focusSeccondInput() {
    try {
        var ins = $('input:text:not([onclick])')
        if (ins.length > 1)
            ins[1].focus()
        else
            ins[0].focus()
    } catch (e) {} // some ie bug
}

function focusTitleInput() {
    try {
        if( $('#id_title') ){
        $('#id_title').focus();
        };
    } catch (e) {} // some ie bug
}

function make_close_errors_handlers() {
    $(".hideErrorContainer a").click
    (
        function()
        {
            $(this).parent().parent().hide();
            return false;
        }
    );
}
var click_login_button = function() {
    if(typeof(click_login_button_override) != 'undefined' && click_login_button_override) {
        click_login_button_override();
    } else {
        popup.submitPopup('login_form_layer');
    }
}
var popup = {
    courtineId: "courtine",
    courtineOpacity: "0.5",
    courtineZindex: "2000",
    courtineBackgroundColor: "#000000",
    popupClassName: "boxLayer",
    popupZindex: "2001",
    curPopupId: null,
    scrollTo: [0,0],
    popupsCount: 0,
    showModerationPopup: function(type, id) {
        $('#moderation_form').attr('action', '/moderation/request/'+type+'/'+id+'/');
        popup.showPopup('moderation');
    },
    showPopup: function(id){
        if($("#"+id) && $("#"+id).hasClass(popup.popupClassName) && $('#'+id).css('display') == 'none'){
            // #16463 FS#4158
            if (id == 'login_form_layer') {
                pageTracker._trackPageview('/register/1/login/');
            }
            if (id == 'register_form_layer') {
                pageTracker._trackPageview('/register/2/form/');
            }
            $("#"+id+" :input").each(function() {
                this.old_value = $(this).val()
            })
            $("#"+id).css("z-index",popup.popupZindex);
            popup.curPopupId = id;
            popup.popupsCount += 1;
            popup.scrollTo = [$(window).scrollLeft(), $(window).scrollTop()];
            popup.popupCourtine();
            popup.justify(id);
            $("#"+id).find('img').load(function() {
                if(!('___sensiloaded' in this)) {
                    this.___sensiloaded = true;
                    popup.justify(id);
                    popup.popupCourtine(id);
                }
            });

            // make larger courtine if the popup makes page longer (#9872):
            popup.popupCourtine(id);
            if('photo_video__load' in window) photo_video__load();
            $("#"+id+" *").trigger('popup_shown');
        }
        popup.regenerateCaptcha(id);
    },
    hidePopup: function(id){
        if($("#"+id) && $("#"+id).hasClass(popup.popupClassName)){
            if(popup.popupsCount > 0) {
                popup.popupsCount -= 1;
            }
            if(!popup.popupsCount) {
                $("#"+popup.courtineId).remove();
            }
            $("#"+id).hide();
            $("#"+id+" :input").each(function() {
                $(this).val(this.old_value);
            })
            popup.cleanErrors(id);
            $("#"+id+" *").trigger('popup_closed');
        }
    },
    cleanErrors: function(id) {
        form = $('#'+id+' form');
        $('#'+id+'_messages').html('');
        form.find('tr').removeClass('showError').find('ul.errorlist').empty();
    },
    popupCourtine: function(id){
        var courtine = $("#"+popup.courtineId);
        if(courtine.length) {
            var courtine = courtine[0]
        } else {
            var courtine = document.createElement("div");
        }
        courtine.id = popup.courtineId;
        width = $(document).width();
        height = popup.getPageSize()[1];
        if($(document).scrollTop() + $("#" + id).height() > height)
            height = $(document).scrollTop() + $("#" + id).height() + 20;

        if($(document.body).height() + 25 > height) height = $(document.body).height() + 25;
        $(courtine).css({
            backgroundColor: popup.courtineBackgroundColor,
            zIndex: popup.courtineZindex,
            position: "absolute",
            top: "0",
            left: "0",
            opacity: popup.courtineOpacity,
            width: "100%",
            height: height + "px"
            //height: $(document).height() + "px"
        })
        document.body.appendChild(courtine);
    },
    justify: function(id){
        $("#"+id).show();
        if ($("#"+id) && $("#"+id).hasClass(popup.popupClassName)) {
            var popupHeight = $("#" + id + "." + popup.popupClassName).outerHeight()
            var popupWidth = $("#" + id + "." + popup.popupClassName).width()
            var winDimensions = popup.getPageSize();
            var positionLayer = 'absolute';
            if(popupHeight < winDimensions[3]){
                var topPosition = (winDimensions[3] / 2) - (popupHeight / 2) + $(document).scrollTop();
                positionLayer = 'absolute';
            } else {
                var topPosition = $(document).scrollTop() + 1;
                positionLayer = 'absolute';
            }
            var leftPosition = $(document).scrollLeft() + ((winDimensions[2] - popupWidth)/2);

            $("#"+id).css({
                top: topPosition + "px",
                left: leftPosition + "px",
                position: positionLayer
            })
        }
    },
    getPageSize: function(){
        var xScroll, yScroll;
        if(window.innerHeight && window.scrollMaxY){
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        }else if(document.body.scrollHeight > document.body.offsetHeight){
        // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        }else{
        // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
        // #10038 - yScroll isn't always correct in IE
        pHeight = $('#'+popup.curPopupId).height();
        if(pHeight + 10 > yScroll) {
            yScroll = pHeight + 30;
        }
        var windowWidth, windowHeight;
        if(self.innerHeight){
            // all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        }else if(document.documentElement && document.documentElement.clientHeight){
            // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        }else if(document.body){
            // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        }else{
            pageHeight = yScroll;
        }
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){
            pageWidth = windowWidth;
        }else{
            pageWidth = xScroll;
        }
        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
        return arrayPageSize;
    },
    submitPopup: function(id, extra_callback, on_success) {
        form = $('#'+id+' form')
        $('#'+id+'_submit').attr('disabled', 'disabled')
        var request=0;
        $.ajax({ url: form.attr('action'), type: 'POST',
          beforeSend: function(req) { request = req; },
          data: form.serializeArray(),
          dataType: 'html',
          success: function (data, textStatus) {
            if(data == '/') {
                location.href = '/';
                return;
            } else if (data == '<success/>') {
                if (id == 'register_form_layer') {
                    pageTracker._trackPageview('/register/3/completed/');
                    location.reload();
                } else {
                    location.reload();
                }
            }
            do_callback = true;
            if(request.getResponseHeader('Content-Type').match('^application/json') == 'application/json') {
                data = eval('('+data+')');
                if(data.result == 'login') {
                    popup.hidePopup(id)
                    popup.showPopup('login_form_layer')
                    id = 'login_form_layer'
                    form = $('#login_form_layer form')
                    data = data.html
                }
                if(data.result == 'transfer') {
                    do_callback = false;
                    popup.hidePopup(id);
                    $('#transfer_form_layer').remove()
                    var box_layers = $('.box_layers');
                    if(!box_layers.length) {
                        box_layers = $('#basicLinks');
                    }
                    box_layers.append($(data.html));
                    popup.showPopup('transfer_form_layer');
                    id = 'transfer_form_layer';
                    form = $('#transfer_form_layer form');
                    data = data.messages
                }
                if(data.result == 'redirect') {
                    location = data.href;
                    return;
                }
                if(data.result == 'step2') {
                    popup.cleanErrors(id);
                    register_form_do_step2();
                    return;
                }
            if (extra_callback && do_callback) extra_callback(data)
            }
            if(data == '' || data == '<success/>') {
                if(on_success) {
                    on_success();
                }
                location = location.href.split('#')[0]
                return
            }

            document.r = data;

            data = $(data);
            var j_data = {};
            popup.cleanErrors(id);
            var msg = data.not('dt');
            var errors = false;
            data.find('dt').each(function() {
                var item = $(this);
                errors=true;
                j_data[item.text()] = item.next().find('li');
            });
            msg.appendTo($('#'+id+'_messages'));

            form.find('tr').each(function() {
                var tr=$(this);
                var errors = j_data[ tr.find(':input:first').attr('name')];
                if (errors) {
                    tr.addClass('showError').find('ul.errorlist').empty().append(errors);
                } else {
                    tr.removeClass('showError').find('ul.errorlist').empty();
                }
            });
            $('#'+id+'_submit').removeAttr('disabled')
            popup.justify(id);
            popup.popupCourtine(id);
            popup.regenerateCaptcha(id);
        }});
    },
    regenerateCaptcha: function(id) {
        $('#'+id+'_captcha').attr('src', '/captcha.png?z='+Math.floor(Math.random()*1000001));
        $('#'+id+'_captcha_input').val('');
    }
}

