var sacc = 0;
var scrollPosition = 0;
var sclick = 0;
var issearch = 0;
var gAutoPrint = true;
var overlayData = null;

function printSpecial() {
    window.print();
/*
    if (document.getElementById != null) {
        var html = '<HTML>\n<HEAD>\n';

        if (document.getElementsByTagName != null) {
            var headTags = document.getElementsByTagName("head");
            if (headTags.length > 0)
                html += headTags[0].innerHTML;
        }
        html += '<style type="text/css">body{background:none;}</style>'
        html += '\n</HE' + 'AD>\n<BODY>\n';

        var printReadyElem = document.getElementById("printReady");

        if (printReadyElem != null) {
            html += printReadyElem.innerHTML;
        }
        else {
            alert("Could not find the printReady section in the HTML");
            return;
        }

        html += '\n</BO' + 'DY>\n</HT' + 'ML>';

        var printWin = window.open("", "printSpecial");
        printWin.document.open();
        printWin.document.write(html);
        printWin.document.close();
        if (gAutoPrint)
            printWin.print();
    }
    else {
        alert("Sorry, the print ready feature is only available in modern browsers.");
    }
*/
}

function submitenter(myfield, e) {
    $('#reset').attr('value', '1');
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13) {
        return false;
    }
    else
        return true;
}

$('document').ready(function () {

    //Consignment Notes
    $('#consignment_note_text').limitChars({ 'chars': 1000, 'haltInputOnLimit': true });

    //Genres
    $('#fld_genres').limitChars({ 'chars': 500, 'haltInputOnLimit': true });

    //MagicZoom Options
    if (typeof ($('#fld_email_none_y')) != 'undefined') {
        $('#fld_email_none_y').click(function () {
            $(".email_options").show();
        });
    }

    if (typeof ($('#fld_email_none_n')) != 'undefined') {
        $('#fld_email_none_n').click(function () {
            $(".email_options").hide();
        });
    }

    if (typeof (MagicZoomPlus) != 'undefined') {
        MagicZoomPlus.options = {
            'zoom-position': 'bottom',
            'opacity-reverse': true
        }
    }

    //Fancybox Photo Gallery
    if (typeof ($.fancybox) != 'undefined') {
        $('a.pgallery').fancybox({
            'transitionIn': 'none',
            'transitionOut': 'none',
            'titlePosition': 'over',
            'titleFormat': function (title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
            } 
        });
    }

    // Sortable tables needs classname of "sortable"
    $('.sortable').tablesorter();

    // Datefields needs a classname of "datepicker"
    $('.datepicker').datepicker();

    // Accordion needs a classname of "accordion"

    $("#accordion").accordion({ autoHeight: false });
    if (issearch == 1) {
        $("#accordion").accordion("option", "active", sacc)
        $("#search_content").css('visibility', 'visible');
        if (scrollPosition > 0) {
            $("html").animate({ scrollTop: scrollPosition }, "slow");
        }
    }

    // Style tabstrip
    $('#main').css({ 'width': '95%', 'margin': '0px auto' });
    $('.apptabstrip').addClass('ui-tabs');
    $('.apptabstrip ul').addClass('ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all');
    $('.apptabstrip ul li').addClass('ui-state-default ui-corner-top');
    $('.apptabstrip ul li.sel').addClass('ui-state-focus ui-tabs-selected ui-state-active');
    $('.ui-state-default').hover(
        function () {
            $(this).addClass('ui-state-hover');
        },
        function () {
            $(this).removeClass('ui-state-hover');
        }
    );

    // Default value for search box
    $('#q').val('Search');

    // Style buttons
    $('input:submit').button().css('margin', '2px');
    $('input:button').button().css('margin', '2px');
    $('a.button').button().css('margin', '2px');
    // Style input boxes
    $('input:text, input:password').addClass('ui-widget-content');
    $('select, textarea').addClass('ui-widget-content');

    /*
    * setup dialog
    ************/
    $('#popup').dialog({
        autoOpen: false,
        width: 550,
        height: 400,
        modal: true,
        resizable: true,
        open: function (event, ui) {
            $("#popup").html(overlayData);
        },
        close: function (event, ui) {
            overlayData = null;
        }
    });

    $('#advnonfirearm').click(function () {
        $("#class").find('option:first').attr('selected', 'selected');
    });

});

function closeUIDialog() {
    $('.ui-dialog-titlebar-close').trigger('click');
}

function parseId(id) {
    var id = id.split(':');
    var retval = '{';
    for (i = 0; i < id.length; i++) {
        if (i < id.length - 1) { var comma = ','; } else { var comma = ''; }
        var kv = id[i].split('-');
        retval += '"' + kv[0] + '":"' + kv[1] + '"' + comma;
    }
    retval += '}';
    return eval('(' + retval + ')');
}

function openDlg(title, url) {
    /*
    $('<iframe frameborder="0" id="externalSite" class="externalSite" src="' + url + '"/>').dialog({
            title: title,
            autoOpen: true,
            width: 400,
            height: 300,
            modal: true,
            resizable: true
        });
    */
    overlayData = getIframe(url);
    $('#popup').dialog({ title: title });
    $('#popup').dialog("open")
}

function getIframe(url) {
    return '<iframe src="' + url + '" id="externalSite" class="externalSite" width="500px" height="350px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

function bidstatus(itemid, status) {
    var lot = $('#i' + itemid).attr('class').match(/bidlot\d+/);

    if (!!lot) {
        $('.' + lot + ' span').html(status);
    } else {
        $('#i' + itemid + ' span').html(status);
    }

    closeUIDialog();
    alert('Thanks. Your bid has been saved. When you are finished saving your bids, make sure to click the SUBMIT YOUR BIDS NOW button to officially place your bids with RIA.');
}

function updatebidstatus(itemid, status, amount) {
    $('#i' + itemid + ' span').html(status);
    $('#b' + itemid + ' span').html('$' + addCommas(amount));
    closeUIDialog();
    alert('Thanks. Your bid has been saved. When you are finished saving your bids, make sure to click the SUBMIT YOUR BIDS NOW button to officially place your bids with RIA.');
}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function wishstatus(target, status, url) {
    var lot = $('#' + target).attr('class').match(/wlot\d+/);

    if (!!lot) {
        $('.' + lot + ' span').html(status);
        $('.' + lot).attr('href', url);
    } else {
        $('#' + target + ' span').html(status);
        $('#' + target).attr('href', url);
    }
    closeUIDialog();
}

function unwish(cid, wid) {
    if (confirm('Are you sure you want to remove this item from your wishlist?')) {
        $.ajax({
            url: '/ajax/__ria.aspx',
            data: {
                action: 'unwish',
                cid: cid,
                wid: wid,
                r: randy()
            },
            success: function (data) {
                var lot = $('#' + data.cid).attr('class').match(/wlot\d+/);

                if (!!lot) {
                    $('.' + lot).attr('href', data.url);
                    $('.' + lot + ' span').html('Add');
                } else {
                    $('#' + data.cid).attr('href', data.url);
                    $('#' + data.cid + ' span').html('Add');
                }
            }
        });
    }
}

function unbid(cid, cartid) {
    $.ajax({
        url: '/ajax/__ria.aspx',
        data: {
            action: 'unbid',
            cid: cid,
            cartid: cartid,
            r: randy()
        },
        success: function (data) {
            var lot = $('#' + data.cid).attr('class').match(/bidlot\d+/);

            ubid();

            if (!!lot) {
                $('.' + lot + ' span').html('Add');
            } else {
                $('#' + data.cid + ' span').html('Add');
            }

            closeUIDialog();
        }
    });
}

function ubid() {
    $.ajax({
        url: '/ajax/__ria.aspx',
        data: {
            action: 'ubids',
            r: randy()
        },
        success: function (data) {
            $('#ubids').html(data);
        }
    });
}

function pop_custom(str, width, height) {
    custom = window.open(str, "custom", "location=0,toolbar=0,left=2,top=103,menubar=1,scrollbars=1,resizable=1,width=" + width + ",height=" + height);
    custom.focus();
}

/*
* Generate a random number
*/
function randy() {
    return Math.random();
}

(function ($) {
        $.fn.limitChars = function (options) {
            //vars
            var code, currentChars, remainingChars, counterSpan, parentForm;
            
            //default options
            var defaults = {
                'chars'             : 1000,
                'showCountdown'     : true,
                'overLimitColor'    : '#ff0000',
                'haltInputOnLimit'  : false,
                'preventSubmission' : true
            };
            var options = $.extend(defaults, options);
            
            //Countdown area has a css class of: .limitCharsCountdown
            if(options.showCountdown){
                $(this).after('<div class="limitCharsCountdown">Characters remaining: <span>' + options.chars + '</span></div>');
            }
            
            //Count 'em
            $(this).keyup(function(e){
                    code = e.keyCode || e.which;
                    checkCount($(this));
            });
            $(this).keydown(function(e){
                    code = e.keyCode || e.which;
                    checkCount($(this));
            });
            
            var checkCount = function(obj){
                    currentChars = obj.val().length;
                    remainingChars = options.chars - currentChars;
                    counterSpan = obj.next().find('span')
                    
                    
                    if(options.showCountdown){
                        counterSpan.html(remainingChars);
                    }
                    
                    if(code != 8 && remainingChars <= 0){
                        counterSpan.css({'color':options.overLimitColor});
                        
                        if(options.preventSubmission){
                            parentForm = $(this).closest("form");
                            parentForm.submit(function(){
                                    return false;
                            });
                        }
                        
                        if(options.haltInputOnLimit){
                            return false;
                        }
                    }else if(remainingChars > 0){
                        counterSpan.css({'color':'inherit'});
                        
                        if(options.preventSubmission){
                            parentForm = $(this).closest("form");
                            parentForm.unbind('submit');
                        }
                    }
            };
            
        }
})(jQuery);
