/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4259 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */

(function($){

$.dimensions = {
    version: '1.2'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){

    // innerHeight and innerWidth
    $.fn[ 'inner' + name ] = function() {
        if (!this[0]) return;

        var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
            borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

        return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
    };

    // outerHeight and outerWidth
    $.fn[ 'outer' + name ] = function(options) {
        if (!this[0]) return;

        var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
            borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

        options = $.extend({ margin: false }, options || {});

        var val = this.is(':visible') ?
                this[0]['offset' + name] :
                num( this, name.toLowerCase() )
                    + num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
                    + num(this, 'padding' + torl) + num(this, 'padding' + borr);

        return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
    };
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
    $.fn[ 'scroll' + name ] = function(val) {
        if (!this[0]) return;

        return val != undefined ?

            // Set the scroll offset
            this.each(function() {
                this == window || this == document ?
                    window.scrollTo(
                        name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
                        name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
                    ) :
                    this[ 'scroll' + name ] = val;
            }) :

            // Return the scroll offset
            this[0] == window || this[0] == document ?
                self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
                    $.boxModel && document.documentElement[ 'scroll' + name ] ||
                    document.body[ 'scroll' + name ] :
                this[0][ 'scroll' + name ];
    };
});

$.fn.extend({
    position: function() {
        var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;

        if (elem) {
            // Get *real* offsetParent
            offsetParent = this.offsetParent();

            // Get correct offsets
            offset       = this.offset();
            parentOffset = offsetParent.offset();

            // Subtract element margins
            offset.top  -= num(elem, 'marginTop');
            offset.left -= num(elem, 'marginLeft');

            // Add offsetParent borders
            parentOffset.top  += num(offsetParent, 'borderTopWidth');
            parentOffset.left += num(offsetParent, 'borderLeftWidth');

            // Subtract the two offsets
            results = {
                top:  offset.top  - parentOffset.top,
                left: offset.left - parentOffset.left
            };
        }

        return results;
    },

    offsetParent: function() {
        var offsetParent = this[0].offsetParent;
        while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
            offsetParent = offsetParent.offsetParent;
        return $(offsetParent);
    }
});

function num(el, prop) {
    return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};

})(jQuery);

function hideDefaultInputText(e){
    var oldText = null;
    var focusNo = null;
    $(e).focus(function(){
        if(focusNo==null){
            focusNo+=1;
            oldText = $(this).val();
            $(this).val("");
        }else{
            if($(this).val()==oldText){
                $(this).val("");
            }
        }
    })
    $(e).blur(function(){
        if($(this).val()==""){
            $(this).val(oldText);
        }
    })
}

function handle_error(elem_id, data) {
    if (data.error) {
        var target = $('#'+elem_id);
        if (!target.length) target = $('#'+elem_id+'0');
        if (target.length) target.html('<span style="color:red;font-size:xx-small">counter error:'+data.error+'</span>');
        return true;
    }
    return false;
}

function get_count(url, elem_id, nofill) {
    try {
        $.getJSON(url + '?t=' + new Date().getTime(),
            function(data){
                if(nofill)return;
                if (handle_error(elem_id, data)) {
                    //
                } else if (data.count.length == 1) {
                    var value = data.count[0]
                    $('#'+elem_id).text(value);
                    $('#'+elem_id+'0').text(value);
                } else {
                    $.each( data.count, function (i, count) {
                        $('#'+elem_id+i).html(count);
                    });
                }
            });
    } catch (e) {
      // some error with AJAX (AdBlock?)
    };
}

function get_ctr(elem_id, site, oid) {
    try {
      $.getJSON('/counter/read/advert_all_impressions/'+site+'/'+oid+'/' + '?t=' + new Date().getTime(), function(data) {
          var impressions_cnt = data.count[0];
          if(impressions_cnt != 0 && !handle_error(elem_id, data)) {
              $.getJSON('/counter/read/advert_all_views/'+site+'/'+oid+'/' + '?t=' + new Date().getTime(), function(data) {
                  if(!handle_error(elem_id, data)) {
                      var views_cnt = data.count[0];
                      ctr = parseInt(100*views_cnt/impressions_cnt);
                      $('#'+elem_id).text(''+ctr+'%');
                  }
              });
          } else {
              $('#'+elem_id).html('N/A');
          }
      });
    } catch (e) {
      // some error with AJAX (AdBlock?)
    }
}

function make_count(elem_id, site, name, oid, action, nofill) {
    var newelem = get_count('/counter/'+action+'/'+name+'/'+site+'/'+oid+'/', elem_id, nofill)
}

function make_count_and_read(elem_id, site, name, oid, sum_name, nofill) {
    var newelem = get_count('/counter/write_and_read/'+name+'/'+site+'/'+oid+'/'+sum_name+'/', elem_id, nofill)
}

function make_counts(elem_id_prefix, site, oname, oids, action, nofill) {
    var newelem = get_count('/counter/'+action+'/'+oname+'/'+site+'/'+oids.join(',')+'/', elem_id_prefix, nofill)
}

function make_count_with_redirect( site, name, oid, href ) {
    /* Makes count request using jQuery and after it is proccessed,
     * either with error or not, it redirects to new page.
     * Basically it holds down synchronous redirect before asynchronous
     * request is finished.
     * It's used in e.g. counting 'go to dealer's website' link click on
     * ad details page.
     * */
    var url = '/counter/write/'+name+'/'+site+'/'+oid+'/';
    $.ajax({
        type: "GET",
        url: url,
        data: "t=" + new Date().getTime(), // IE's caching hacked, #4967
        success: function( response ) {
            document.location = href;
        },
        error: function() {
            document.location = href;
        }
    } );
}

function make_count_with_submit( site, name, oid, form ) {
    /* Similar to make_count_with_redirect but with form submit,
     * used in e.g. ad details email forms
     * */
    var url = '/counter/write/'+name+'/'+site+'/'+oid+'/';
    $.ajax( {
        type: "GET",
        url: url,
        data: "t=" + new Date().getTime(), // IE's caching hacked, #4967
        success: function( response ) {
            $( form ).submit();
        },
        error: function() {
            $( form ).submit();
        }
    } );
}

// PAA Online Products Scripts
var PAA_online_products = {
    expandViewId: '#expand_view', //expand all online options button id
    simpleViewId: '#simple_view', //back to simple view button id
    simpleSummary: {
        id: '#simple_summary',
        packageNameId: '#package_name',
        packageDescriptionId: '#package_description',
        onlineCostId: '#online_cost',
        groupSufix: '_group',
        labelSufix: '_label',
        hintSufix: '_hint',
        clearData: function(){
            $(PAA_online_products.simpleSummary.packageNameId).html('');
            $(PAA_online_products.simpleSummary.packageDescriptionId).html('');
            $(PAA_online_products.simpleSummary.onlineCostId).html('');
        }
    },
    advancedSummary: {
        id: '#advanced_summary',
        productListId: '#advanced_summary_container',
        totalPriceId: '#total_price'
    },
    temporaryTotalPrice: '',
    adPreviewId: '#preview_row',
    query: {
        allRadioInput: '#cfg_onlinepackages input[type="radio"]',
        allCheckedRadioInput: '#cfg_onlinepackages .newproduct input[type="radio"][checked]',
        allCheckboxInput: '#cfg_onlineproducts input[type="checkbox"]',
        allCheckedCheckboxInput: '#cfg_onlineproducts .newproduct:not(.obligatory) input[type="checkbox"][checked]'
    },
    nullPriceText: 'Free',
    previewClasses: '',
    oldPreviewClass: '',
    nextStepButtonId: '#continue_button_payment',
    noThanksLinkClass: '.no_thanks_button',
    defaultPackageId: '#id_PCKG-00',
    clearRadio: function(e){
        $(e).each(function(){
            $(this).removeAttr('checked');
            $(this).val('');
            if ($('#' + $(this).attr('id') + '' + PAA_online_products.simpleSummary.groupSufix).hasClass('current')) {
                $('#' + $(this).attr('id') + '' + PAA_online_products.simpleSummary.groupSufix).removeClass('current');
            }
        })
        PAA_online_products.temporaryTotalPrice='';
    },
    clearCheckbox: function(e){
        $(e).each(function(){
            $(this).removeAttr('checked');
            $(this).val('')
        })
        $(PAA_online_products.advancedSummary.productListId).html('');
        PAA_online_products.previewClasses = '';
        PAA_online_products.temporaryTotalPrice='';
    },
    clearPreviewStyle: function(e){
        $(e).attr('class', '');
    },
    addPackageStyleToPreview: function(e, second){
        var _id = '#' + $(e).attr('id').replace(PAA_online_products.simpleSummary.groupSufix, '');
        var package_name = $(_id + '' + PAA_online_products.simpleSummary.labelSufix).html();
        var package_description = $(_id + '' + PAA_online_products.simpleSummary.hintSufix).text()
        var package_price = $(_id).next().html().replace('(', '').replace(')', '');
        $(PAA_online_products.adPreviewId).attr('class', $('#setClass_' + _id.replace('#', '')).attr('class'));
        PAA_online_products.oldPreviewClass = $('#setClass_' + _id.replace('#', '')).attr('class');
        PAA_online_products.clearRadio(PAA_online_products.query.allRadioInput);
        PAA_online_products.clearCheckbox(PAA_online_products.query.allCheckboxInput)
        $(_id).attr('checked', true);
        $(_id).val('on');
        if (second) {
            $('#' + $(e).attr('id') + '' + PAA_online_products.simpleSummary.groupSufix).addClass('current');
        }
        else {
            $(e).addClass('current');
        }
        PAA_online_products.clearCheckbox(PAA_online_products.query.allCheckboxInput);

        $(PAA_online_products.simpleSummary.packageNameId).text(package_name);
        $(PAA_online_products.simpleSummary.packageDescriptionId).text(package_description);
        if (package_price == '$0' || package_price == '$0.00') {
            $('#only').hide();
            $(PAA_online_products.advancedSummary.totalPriceId).text(PAA_online_products.nullPriceText);
            $('#continue_payment_button').text('Continue');
        }
        else {
            $('#only').show();
            $('#continue_payment_button').text('Payment');
            $(PAA_online_products.advancedSummary.totalPriceId).text(package_price);
        }
        if($(PAA_online_products.advancedSummary.totalPriceId).parent().css('display')=='none'){
            $(PAA_online_products.advancedSummary.totalPriceId).parent().show();
        }
        $(PAA_online_products.advancedSummary.productListId).html('');
    },
    selectPackage: function(e){
        $(e).click(function(){
            PAA_online_products.addPackageStyleToPreview($(this));
        });
    },
    noProductSelectedSubmit: function(e){
        $(e).click(function(){
            PAA_online_products.addPackageStyleToPreview($(PAA_online_products.defaultPackageId));
            $('#advert_form').submit();
            return false;
        });
    },
    selectProduct: function(e){
        $(e).each(function(){
            var _prod_name = $(this).parent().find('label').text();
            var _prod_price = $(this).parent().find('.price').text().replace('(', '').replace(')', '');
            if (_prod_price.replace('$', '') == '0') {
                _prod_price = PAA_online_products.nullPriceText;
            }
            if (this.checked) {
                $(PAA_online_products.advancedSummary.productListId).append('<tr class="' + $(this).attr('id') + '"><td class="name">' + _prod_name + '</td><td class="price">' + _prod_price + '</td></tr>');
                if (PAA_online_products.previewClasses == '') {
                    PAA_online_products.previewClasses = $('#setClass_' + $(this).attr('id')).attr('class');
                }
                else {
                    PAA_online_products.previewClasses = PAA_online_products.previewClasses + ' ' + $('#setClass_' + $(this).attr('id')).attr('class');
                }
                $(PAA_online_products.adPreviewId).attr('class', PAA_online_products.previewClasses);
                PAA_online_products.oldPreviewClass = '';
                PAA_online_products.totalPrice(PAA_online_products.advancedSummary.productListId);
                PAA_online_products.clearRadio(PAA_online_products.query.allRadioInput);
                PAA_online_products.simpleSummary.clearData();
            }
            $(this).click(function(){
                if (this.checked) {
                    PAA_online_products.onlyOneProductFromGroup($(this));
                    $(PAA_online_products.advancedSummary.productListId).append('<tr class="' + $(this).attr('id') + '"><td class="name">' + _prod_name + '</td><td class="price">' + _prod_price + '</td></tr>');
                    if (PAA_online_products.previewClasses == '') {
                        PAA_online_products.previewClasses = $('#setClass_' + $(this).attr('id')).attr('class');
                    }
                    else {
                        PAA_online_products.previewClasses = PAA_online_products.previewClasses + ' ' + $('#setClass_' + $(this).attr('id')).attr('class');
                    }
                    $(PAA_online_products.adPreviewId).attr('class', PAA_online_products.previewClasses);
                    PAA_online_products.oldPreviewClass = '';
                    $(this).val('on');
                }
                else {
                    $(this).removeAttr('checked');
                    $(this).removeAttr('selected');
                    $(this).val('');
                    $('.' + $(this).attr('id')).remove();
                    if (PAA_online_products.previewClasses.split(' ').length == 1) {
                        $('#continue_payment_button').text('Continue');
                        PAA_online_products.previewClasses = PAA_online_products.previewClasses.replace($('#setClass_' + $(this).attr('id')).attr('class'), '');
                    }
                    else {
                        if (PAA_online_products.previewClasses.indexOf($('#setClass_' + $(this).attr('id')).attr('class')) > 0) {
                            PAA_online_products.previewClasses = PAA_online_products.previewClasses.replace(' ' + $('#setClass_' + $(this).attr('id')).attr('class'), '');
                        }
                        else {
                            PAA_online_products.previewClasses = PAA_online_products.previewClasses.replace($('#setClass_' + $(this).attr('id')).attr('class') + ' ', '');
                        }
                    }
                    $(PAA_online_products.adPreviewId).attr('class', PAA_online_products.previewClasses);
                }
                PAA_online_products.totalPrice(PAA_online_products.advancedSummary.productListId);
                PAA_online_products.clearRadio(PAA_online_products.query.allRadioInput);
                PAA_online_products.simpleSummary.clearData();
            })
        })
    },
    onlyOneProductFromGroup: function(e){
        var _groupSuffix = $(e).attr('id').split('_')[2];
        $(PAA_online_products.query.allCheckboxInput).each(function(){
            if ($(this).attr('id').indexOf(_groupSuffix) > -1 && $(this).attr('id') != $(e).attr('id')) {
                $(this).removeAttr('checked');
                $(this).val('');
                $('.' + $(this).attr('id')).remove();
                if (PAA_online_products.previewClasses.split(' ').length == 1) {
                    PAA_online_products.previewClasses = PAA_online_products.previewClasses.replace($('#setClass_' + $(this).attr('id')).attr('class'), '');
                }
                else {
                    if (PAA_online_products.previewClasses.indexOf($('#setClass_' + $(this).attr('id')).attr('class')) > 0) {
                        PAA_online_products.previewClasses = PAA_online_products.previewClasses.replace(' ' + $('#setClass_' + $(this).attr('id')).attr('class'), '');
                    }
                    else {
                        PAA_online_products.previewClasses = PAA_online_products.previewClasses.replace($('#setClass_' + $(this).attr('id')).attr('class') + ' ', '');
                    }
                }
                $(PAA_online_products.adPreviewId).attr('class', PAA_online_products.previewClasses);
            }
        });
    },
    totalPrice: function(e){
        var allPrice = new Array();
        $(e + ' .price').each(function(){
            allPrice.push($(this).text());
        })
        if(allPrice.length > 0){
            var total = 0;
            for (var i = 0; i < allPrice.length; i++) {
                if (allPrice[i] == PAA_online_products.nullPriceText) {
                    total = total + parseFloat(0)
                }
                else {
                    total = total + parseFloat(allPrice[i].replace('$', ''))
                }
            }
            if (total.toFixed(2) == 0) {
                $('#continue_payment_button').text('Continue');
                $(PAA_online_products.advancedSummary.totalPriceId).text(PAA_online_products.nullPriceText);
            }
            else {
                $('#continue_payment_button').text('Payment');
                $(PAA_online_products.advancedSummary.totalPriceId).text('$' + total.toFixed(2));
            }
            if($(PAA_online_products.advancedSummary.totalPriceId).parent().css('display')=='none'){
                $(PAA_online_products.advancedSummary.totalPriceId).parent().show();
            }
        }else{
            $(PAA_online_products.advancedSummary.totalPriceId).parent().hide();
            $(PAA_online_products.advancedSummary.totalPriceId).text('');
            PAA_online_products.temporaryTotalPrice = $(PAA_online_products.advancedSummary.totalPriceId).text();
        }
    },

    expandView: function(e){
        $(e).click(function(){
            $('#cfg_onlinepackages').parent().css({
                'visibility': 'hidden',
                'height': '1px',
                'overflow': 'hidden',
                'margin': '0'
            });
            $('#cfg_onlineproducts').parent().css({
                'visibility': 'visible',
                'height': 'auto',
                'margin': '-1px 0 12px 0'
            });
            $('.add_advert_box').css({
                'padding': '30px 10px'
            });
                        PAA_online_products.clearRadio(PAA_online_products.query.allRadioInput)
                        PAA_online_products.temporaryTotalPrice='';
                        PAA_online_products.simpleSummary.clearData();
                        PAA_online_products.oldPreviewClass = '';
                        $('#only').hide();
                        $(PAA_online_products.advancedSummary.totalPriceId).text(PAA_online_products.nullPriceText);
                        $('#continue_payment_button').text('Continue');

            if($(PAA_online_products.advancedSummary.totalPriceId).text() != ''){
                PAA_online_products.temporaryTotalPrice = $(PAA_online_products.advancedSummary.totalPriceId).text();
                $(PAA_online_products.advancedSummary.totalPriceId).text('');
                $(PAA_online_products.advancedSummary.totalPriceId).parent().hide();
            }else{
                if(PAA_online_products.temporaryTotalPrice != ''){
                    $(PAA_online_products.advancedSummary.totalPriceId).text(PAA_online_products.temporaryTotalPrice);
                    $(PAA_online_products.advancedSummary.totalPriceId).parent().show();
                }
            }
            $(PAA_online_products.expandViewId).hide();
            $(PAA_online_products.simpleViewId).show();
            $(PAA_online_products.advancedSummary.id).show();
            $(PAA_online_products.simpleSummary.id).hide();
            $(PAA_online_products.adPreviewId).attr('class', PAA_online_products.previewClasses);
            return false;
        });
    },

    simpleView: function(e){
        $(e).click(function(){
            $('#cfg_onlineproducts').parent().css({
                'visibility': 'hidden',
                'height': '1px',
                'overflow': 'hidden',
                'margin': '0'
            })
            $('#cfg_onlinepackages').parent().css({
                'visibility': 'visible',
                'height': 'auto',
                'margin-bottom': '12px'
            });
                        PAA_online_products.clearCheckbox(PAA_online_products.query.allCheckboxInput)
                        PAA_online_products.temporaryTotalPrice='';
                        PAA_online_products.simpleSummary.clearData();
                        PAA_online_products.oldPreviewClass = '';
                        $('#only').hide();
                        $(PAA_online_products.advancedSummary.totalPriceId).text(PAA_online_products.nullPriceText);
                        $('#continue_payment_button').text('Continue');

            if($(PAA_online_products.advancedSummary.totalPriceId).text() != ''){
                PAA_online_products.temporaryTotalPrice = $(PAA_online_products.advancedSummary.totalPriceId).text();
                $(PAA_online_products.advancedSummary.totalPriceId).text('');
                $(PAA_online_products.advancedSummary.totalPriceId).parent().hide();
            }else{
                if(PAA_online_products.temporaryTotalPrice != ''){
                    $(PAA_online_products.advancedSummary.totalPriceId).text(PAA_online_products.temporaryTotalPrice);
                    $(PAA_online_products.advancedSummary.totalPriceId).parent().show();
                }
            }
            $(PAA_online_products.simpleViewId).hide();
            $(PAA_online_products.expandViewId).show();
            $('.add_advert_box').css({
                'padding': '10px 10px 30px'
            })
            $(PAA_online_products.simpleSummary.id).show();
            $(PAA_online_products.advancedSummary.id).hide();
            if (PAA_online_products.oldPreviewClass == '') {
                PAA_online_products.clearPreviewStyle(PAA_online_products.adPreviewId);
            }
            else {
                $(PAA_online_products.adPreviewId).attr('class', PAA_online_products.oldPreviewClass);
            }
            return false;
        });
    },
    selected_products: function(packages, products){
        var _checked_packages = $(packages).length;
        var _checked_products = $(products).length;
        if (_checked_packages > 0) {
            PAA_online_products.clearCheckbox(PAA_online_products.query.allCheckboxInput);
            PAA_online_products.addPackageStyleToPreview($(packages), true);
        }
        else
            if (_checked_packages == 0 && _checked_products > 0) {
                $(PAA_online_products.expandViewId).click();
                PAA_online_products.totalPrice(PAA_online_products.advancedSummary.productListId);
            }
        return false;
    },
    init: function(){
        PAA_online_products.noProductSelectedSubmit(PAA_online_products.noThanksLinkClass)
        PAA_online_products.selectPackage('#cfg_onlinepackages  .productSetContainer');
        PAA_online_products.noProductSelectedSubmit('#advert_form_content .info_side .no_product a');
        PAA_online_products.selectProduct(PAA_online_products.query.allCheckboxInput);
        PAA_online_products.expandView(PAA_online_products.expandViewId);
        PAA_online_products.simpleView(PAA_online_products.simpleViewId);
        $('#cfg_onlineproducts').parent().css({
            'visibility': 'hidden',
            'height': '1px',
            'overflow': 'hidden',
            'margin': '0'
        });
        $(PAA_online_products.simpleViewId).hide();
        $(PAA_online_products.advancedSummary.id).hide();
        PAA_online_products.selected_products(PAA_online_products.query.allCheckedRadioInput, PAA_online_products.query.allCheckedCheckboxInput);
    }
}
// End PAA Online Products Scripts

var media_player_callbacks = {};
function playerReady(obj) {
    obj.id = "player_0"; /* allows playing on linux ff, but prevent having more players on 1 page */
    player = document.getElementById(obj.id);
    media_player_callbacks[obj.id](player);
};

function create_player(placeholder, flashvars, w, h, pid, fun) {
    swfobject.embedSWF("/statics/flash/mediaplayer42.swf",
        placeholder, w, h, "9.0.0", false,
        flashvars,
        {"allowfullscreen":"true", "allowscriptaccess":"always", "wmode":"opaque"},
        {id:pid, name:pid},
        function(e) {
            if(!e.success) {
                $('#'+placeholder).show();
            }
        });

    media_player_callbacks[pid] = fun;
};

/*
 * $Id$
 * 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);//.animate({ opacity: 0.7}, 400 );
    },
    loader_done = function(l) {
    l.remove(); //.stop().animate({opacity: 0}, 400, function() { $(this).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 IE6imgMaxWidthFix(imgParentElement,imgMaxWidth){
  if($.browser.msie && $.browser.version=="6.0"){
      $(imgParentElement).each(function(){
          $(this).find("img").each(function(){
              if($(this).width()>imgMaxWidth){
                  $(this).css({
                     "width":imgMaxWidth+"px"
                  });
              }
              $(this).show();
          });
      });
  }
}

/**
 * file: popup.js
 */

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, noCaptcha){
        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');
        }
        if (!!!noCaptcha || noCaptcha !== true){
            popup.regenerateCaptcha(id);
            refreshRecaptcha(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, ul').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"
        })
        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();
            if(popupHeight < winDimensions[3]){
                var topPosition = (winDimensions[3] / 2) - (popupHeight / 2) + $(document).scrollTop();
            } else {
                var topPosition = $(document).scrollTop() + 1;
            }
            var leftPosition = $(document).scrollLeft() + ((winDimensions[2] - popupWidth)/2);

            $("#"+id).css({
                top: topPosition + "px",
                left: leftPosition + "px",
                position: 'absolute' 
            })
        }
    },
    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.replace(location.pathname);
                    return;
                } 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()
                    $('.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();
                }
                /*They said they didn't want this nice redirect
                 without search clouse when moderated. Now keep search #search-url:... */

                if(id == 'moderation')
                    location = location.href;
                else
                    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, ul').each(function() {
                var tr=$(this);
                var errors = j_data[ tr.find(':input:first').attr('name')];
                if (errors) {
                    tr.addClass('showError').find('span.inlineError').empty().append(errors);
                } else {
                    tr.removeClass('showError').find('span.inlineError').empty();
                }
            });
            $('#'+id+'_submit').removeAttr('disabled')
            popup.justify(id);
            popup.popupCourtine(id);
            popup.regenerateCaptcha(id);
        }});
    },
    regenerateCaptcha: function(id) {

        if($('#'+id+'_captcha').length) {
            $('#'+id+'_captcha').attr('src', '/captcha.png?z='+Math.floor(Math.random()*1000001));
            $('#'+id+'_captcha_input').val('');
        } else {
            // its a hack, captcha should be generated by python i guess, but it is not
            // i could fix that better way, but well, all js is going to be refactored...
            // eventually, till then here's a hack with captcha
            $('#id_recaptcha_profile_user p.js_captcha_picture').remove();
            $('#id_recaptcha_profile_user').before('<p class="js_captcha_picture"><img src="/captcha.png?z=' + Math.floor(Math.random()*1000001) + '" alt="" /></p>');
            $('#id_recaptcha_profile_user').val('');
        }
    }
}

toolbar_call = function(path_prefix, path_suffix, show_clipboard, show_login_lay) {
    return function()  {
        var loc = document.location;
        var path = loc.protocol + '//' + loc.host + path_prefix
        if(loc.protocol == 'https:') {
            path = path + 'ssl/';
        }
        var layers = $('.box_layers');
        var menuloader = loader($('.headerMenu'));
        path += path_suffix;
        var timer = (new Date()).getUTCMilliseconds()
        $.getJSON(path, function(data) {
            $.each(data, function(k, v) {
                $('#'+k).append(v).find('.boxLayer').appendTo(layers)
            });

            if (show_clipboard){
                clipboard.init();
            } else if (show_login_lay) {
                popup.showPopup('login_form_layer');
            }
            loader_done(menuloader);
            $(document).trigger('toolbar_loaded');
        });
    }
};


/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                var skin = split[i];
                break;
            }
        }

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = $(e).find('>ul,>ol,div>ul,div>ol');
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
            this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        if ($.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load', function() { self.setup(); });
        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.3'
    };

    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
                i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, add = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            i = $jc.intval(i);
            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }

                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                    alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    return 0;
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }

            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },

        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);

$(document).ready(function() { $('.scriptonly').removeClass('scriptonly') })
function parseUrlParams(url) {
    if(url.indexOf('?') >= 0){
        var params = url.split('?')[1].split('&')
        var rv = {}
        for(var i = 0; i < params.length; i++) {
            var kv = params[i].split('=')
            rv[kv[0]] = kv[1]
        }
        return rv
    }
}
function getCookies() {
    var c = document.cookie.split('; ')
    var cookies = {}
    for(i = 0; i<c.length; i++) {
        var kv = c[i].split('=')
        cookies[kv[0]] = kv.slice(1, kv.length).join('=')
    }
    return cookies
}
function getCookie(name) {
    return getCookies()[name] || '"{}"' //HACK
}

clipboard = {
    items: {},
    asyncEdit: ((typeof(window.clipboard_async_edit)=='boolean')?clipboard_async_edit:true),
    init: function() {
        clipboard.parseCookie()
        $('.clipboard-status .counter').each(clipboard.showCounter)
        $('.clipboard-actions a').each(clipboard.showAction)
        $('.activateClipboardActions .addRemoveSwitch').each(clipboard.showAction)
        if(!('dont_post_clipboard' in window)) {
            clipboard.initForm()
            clipboard.attachPost()
        }

    },
    search_enable: function() {
        $(".clipboard-form-field").remove();
        for (key in clipboard.search_mvd) {
            $('<input type="hidden" name="' + key + '" value="' + clipboard.search_mvd[key] + '" class="clipboard-form-field" />').appendTo('#clipboard-form');
        }
    },
    fixqueryid: function() {
        $('.query2clipboard a').each(function(){
            this.href=this.href.split('id=')[0]+'id='+clipboard.search_id;});
    },
    initForm: function() {
        $("#clipboard-form").remove();
        clipboard.form = $('<form id="clipboard-form" method="post"/>').appendTo('body').get(0);
        clipboard.search_enable();
    },
    showCounter: function() {
      if (/\bclipboard-count-(\w+)\b/.test(this.className)) {
        var self = $(this);
        var type = RegExp.$1;
    var val = 0;
    if (type == 'all') {
      for (var key in clipboard.items)
        val += clipboard.items[key].length;
    }
    else
          val = clipboard.items[type] && clipboard.items[type].length;
        if (!val) {
          self.text('0');
          if (type == 'dealoftheday') {
            self.parents('p.item-type').eq(0).hide();
          }
        } else {
          self.text(val);
          self.parents('p.item-type').eq(0).show();
        }
      }
    },
    extractItemFromUrl: function(url) {
        return parseUrlParams(url)
    },
    parseCookie: function() {
        //fix safari cookie handling (comma breaks it)
        eval('clipboard.items = (' + getCookie(clipboard_cookie_name).substring(1, getCookie(clipboard_cookie_name).length-1).replace(/\|/g,',') + ');')
    },
    isActionEnabled: function(action, item) {
        var enabled = false
        switch(action) {
            case 'add'   : enabled = !clipboard.containsItem(item); break;
            case 'remove': enabled = clipboard.containsItem(item); break;
            case 'edit'  : break;
        }
        return enabled
    },
    showAction: function() {
        if (this.tagName == 'A') {
            var item = clipboard.extractItemFromUrl(this.href);
        } else {
            var $control_box = $(this).siblings('.control-box');
            var item = {
                'type': $('.object_type', $control_box).text(),
                'id': $('.object_id', $control_box).text()
            };
        }
        var action = this.className.split(/\s+/)[0];
        this.title = $(this).text();
        if(clipboard.isActionEnabled(action, item)) {
            $(this).addClass('enabled');
        } else {
            $(this).removeClass('enabled');
        }
    },
    attachPost: function() {
         $('.clipboard-actions a').unbind('click').bind('click', clipboard.doPost);//.live('click', clipboard.doPost);
         $(document).bind('listing_was_refreshed', function(){ 
            $('.clipboard-actions a').each(clipboard.showAction);
         });
    },
    containsItem: function(item) {
        var a = clipboard.items[item.type];
        if (a) {
            for (var i = 0; i < a.length; i++) {
                if(a[i] == item.id) {
                    return true;
                }
            }
        }
        return false;

    },
    doPost: function(event) {
        event.preventDefault();
        clipboard.form.action = this.href;
        var $event_target = $(event.target);
        if (clipboard.asyncEdit) {
            $.ajax({
                url: clipboard.form.action,
                data: $(clipboard.form).serialize(),
                type: "POST",
                dataType: "json",
                success: function(data, textStatus) {
                    if (data.query_id) {
                        clipboard.search_id = data.query_id;
                        clipboard.fixqueryid();
                    }
                    if (typeof(data.clipboard_count) !== "undefined") {
                        $('#js-clipboardCount').html(data.clipboard_count);
                    }
                    clipboard.init();
                    var target_event = $event_target.attr(data.save_status + "-event");
                    if (typeof target_event !== "undefined") {
                        $event_target.trigger(target_event);
                    }
                }
            });
            try {
                $("a.all-saved-ads").each(function () {
                    var type = clipboard.form.action.split("?")[1].split("&")[0].split("=")[1];
                    this.href = "/clipboard/?tab=" + (clipboard.form.type || type || "");
                });
            } catch (e) {
                // pass
            }
        } else {
            clipboard.form.submit();
        }
    },
    getItems: function(type) {

    }
}

$(document).ready(function() {
    if('clipboard_toolbar_events' in window) {
        // clipboard_toolbar_events - obsolete name; now we check if user is logged by cookie instead of waiting for toolbar
        if(!getCookies()['user_logged']) {
            $('.clipboard-actions a').each(function() {
                $(this).attr('onclick', '')
            });
            window.dont_post_clipboard = true;
        }
    }

    $(document).bind('toolbar_loaded', function() {
        clipboard.init();
        $('.activateClipboardActions').each(function() {
            var $control_box = $('.control-box', this);
            var site_name = $('.site_name', $control_box).text();
            var object_id = $('.object_id', $control_box).text();
            var remove_url = $('.remove_url', $control_box).text();
            var add_url = $('.add_url', $control_box).text();
            $('.addActivator', this).click(function() {
                make_count('counter', site_name, 'save_ad_action', object_id, 'write', true);
                var fake_a = {
                    'href': add_url
                };
                clipboard.doPost.apply(fake_a, null);
            });
            $('.removeActivator', this).click(function() {
                var fake_a = {
                    'href': remove_url
                };
                clipboard.doPost.apply(fake_a, null);
            });
        });
        $('.clipboard-status .counter').each(clipboard.showCounter);
    });
});

function doSubmit() {
    window.open("","myWindow","width=640,height=480");
    form = document.getElementById('newsletter')
    form.submit("ctlEMRSubmit");
}
function changeValue() {
    document.getElementById('email').value = '';
}
$(document).ready(function() {
    var activate_form = function(container) {
        var $control_box = $('.control-box', container.parent());
        var loader = $('.loader', $control_box).html();
        var $form = $(this);
        $('label[for=id_terms_and_conditions]', $form).parents('th:first').remove();
        $('input[name=terms_and_conditions]', $form).parents('td:first').attr('colspan', 2);
        $('input[name=subscription_type]', $form).change(function() {
            var value = $(this).val();
            var $mobile_row = $('input[name=mobile_phone]', $form).parents('tr:first');
            if (value == 'email_and_mobile') {
                $mobile_row.show();
            } else {
                $mobile_row.hide();
            }
        });
        var $submit_button = $('button[type=submit]', $form);
        $form.submit(function() {
            $submit_button.attr('disabled', 'disabled');
            var url = $form.attr("action") + '?' + new Date().getTime() + Math.random();
            var form_data = $form.serializeArray();
            $form.replaceWith(loader);
            container.load(url, form_data, function() {
                var $container = $(this);
                $('.newsletter-box', $container).each(function() { activate_form.apply(this, [$container]); });
            });
            return false;
        });
        $submit_button.removeAttr('disabled');
    };
    $('.activateNewsletter').each(function() {
        var $container = $('.ajaxBox', this);
        $('.newsletter-box', $container).each(function() { activate_form.apply(this, [$container]); });
    });

    refreshRecaptcha = function (id) {
        recaptcha_field = $('#'+id+' [name=recaptcha_field]');
        if (typeof(recaptcha_field)!='undefined' && recaptcha_field.size() > 0) {
            recaptcha_id = recaptcha_field.attr('id');
            recaptcha_settings = recaptcha_fields[recaptcha_id];
            Recaptcha.create(recaptcha_public_key, recaptcha_id, recaptcha_settings);
        }
    };
});

