$(document).ready(function() {
	$('table tr:odd').addClass('tr-odd');
});
$(function () {
	$('#liveauc-table .add-tolist').live('click', function() {
		$(this).parents('td').html('<a href="#" class="remove-fromlist">remove</a>');
		return false;
	});
	$('#liveauc-table .remove-fromlist').live('click', function() {
		$(this).parents('td').html('<input type="checkbox" class="check add-tolist" />');
		return false;
	});

	$('#step2-content .tabs ul li').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});

	$('input.invoice-button').click(function() {
        $(this).attr('checked', true);
		$('#paymentblock .content').removeClass('nocontent');
        $('#main-step-1, #main-step-2').hide();
		if ($(this).hasClass('invoice-yes')) {
			$('input.invoice-no').attr('checked', false);
			$('#pay-step-head').find('.ybb').addClass('ybb-grey');
			$('#pay-step-head').find('select').removeClass('red').attr('disabled', true);
			$('#main-step-1').show();
		} else if ($(this).hasClass('invoice-no')) {
			$('input.invoice-yes').attr('checked', false);
			$('#pay-step-head').find('.ybb').removeClass('ybb-grey');
			$('#pay-step-head').find('select').addClass('red').attr('disabled', false);
			$('#paymentblock .content').addClass('nocontent');
            $('#main-step-2').show();
		}
    });
    
	$('#payment-method-chooser-form').submit(function() {
		var select_value = $(this).find('select').val();
		if (select_value=='unselected') {
			return false;
		};
		$('#step2-content .tabs ul li').removeClass('active');
		$('#tab-'+ select_value).addClass('active');
		$('#main-step-2').show();
		$('#paymentblock .content').removeClass('nocontent');
		return false;
	});
    
	$('#main-step-1 .yellow-field').keyup(function() {
		if($(this).val().length) {
			$('#proceed-to-step-2').attr('disabled', false)
		} else {
			$('#proceed-to-step-2').attr('disabled', true);
		}
	});

	$('.whitebox .toggler').live('click', function() {
		if ($(this).hasClass('toggler-opened')) {
			$(this).removeClass('toggler-opened').addClass('toggler-closed').html('Expand this Panel');
		} else {
			$(this).addClass('toggler-opened').removeClass('toggler-closed').html('Collapse this Panel');
		};
		$(this).prev('.toggled-content').toggle('fast');
	});
	$('#main-nav ul li, #loginbar .logged .nav li').hover(function() {
		$(this).find('.dropdown:eq(0)').slideDown('fast');
		$(this).find('a:eq(0)').addClass('hover');
	}, function() {
		$(this).find('.dropdown:eq(0)').slideUp('fast');
		$(this).find('a:eq(0)').removeClass('hover');
	});

	$('#categories ul li .title').click(function() {
		if ($(this).parents('li:eq(0)').hasClass('opened') ) {
            $('#categories ul li').removeClass('opened');
			$('#categories ul li .dropdown').hide('normal');
			return false;
		};

        if (!$(this).next('div.dropdown').length)
        {
            return true;
        }
        
        $('#categories ul li').removeClass('opened');
		$('#categories ul li .dropdown').hide('normal');
		$(this).parents('li:eq(0)').addClass('opened');       
		$(this).parents('li:eq(0)').find('.dropdown').show('normal');

        return false;
	});
	$('#categories ul li .title').hover(function() {
		$(this).addClass('title-hover');
	}, function() {
		$(this).removeClass('title-hover');
	});

	$('#fixedbar .tab .head').click(function() {
		var tab = $(this).parents('.tab:eq(0)');

		if ($.browser.opera) {
				if (tab.hasClass('tab-opened')) {
				var other_tabs = $('#fixedbar .tab-opened').not(tab);
				//var speed = ;
				other_tabs.hide();

				setTimeout(function () {
					other_tabs.show();
				}, 85);
			}

			tab.toggleClass('tab-opened');
			tab.find('.content:eq(0)').toggle();

		} else {
			tab.toggleClass('tab-opened');

			if (tab.hasClass('tab-opened')) {
				tab.find('.content:eq(0)').slideDown();
				// $('#fixedbar .tab-opened').not(tab).css('height', '0');
			} else {
				tab.find('.content:eq(0)').slideUp();
			}

		};

	});

	$('.bubble').hover(function() {
		$('.bubble .tooltip:eq(0)').css({'visibility':'hidden'});
		$(this).find('.tooltip:eq(0)').css({'visibility':'visible'});
	}, function() {
		$(this).find('.tooltip:eq(0)').css({'visibility':'hidden'});
	});

	$('#main-lists .tabs ul li').hover(function() {
		$(this).find('div.in:eq(0)').addClass('in-hover');
	}, function() {
		$(this).find('div.in:eq(0)').removeClass('in-hover');
	});

	$('table tr').hover(function() {
		if ($(this).hasClass('cnt')) {
			return;
		};
		$(this).addClass('tr-hover');
	}, function() {
		$(this).removeClass('tr-hover');
	});

	$('#main-lists table tr').hover(function() {
		$(this).find('.rating').find('.full').removeClass('full').addClass('empty');
	}, function() {
		$(this).find('.rating').find('.empty').removeClass('empty').addClass('full');
	});

	$('.top-backordered p').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
});

$(function() {
//AUCTION Table
	

    $('#user-sidenav ul li a.link').click(function(){

        var form = $(this).attr('href').replace('/account/index/formName/', '');
        $('#accountForms').children().hide();
        $('#accountForms #'+form).show();
        return false;
    })

    $('#step2-content div.tabs ul li').click(function(){
        $('#step2-content div.tabs ul li').removeClass('active');
        $(this).addClass('active');
        var id = this.id.replace('tab-','');
        $('div.paymentForm').hide();
        $('div#'+id).show();
    })

    if($('div.paymentForm').length) {
        $('div.paymentForm:gt(0)').hide();
        var id = $('div.paymentForm:eq(0)').attr('id');
        $('#step2-content div.tabs ul li#tab-'+id).addClass('active');
    }

    if(jQuery.fn.qtip) {
      $.fn.qtip.styles.forms = { // Last part is the name of the style
        color: 'black',
        textAlign: 'center',
        border:{
            width: 10,
            radius: 10,
            color:'#739AB5'
        },
        tip: true,
        background: '#EFEFEF'
    }};

    options = {
            style:'forms',
//            show: 'focus',
//            hide: 'blur',
            position: {
            corner: {
                 target: 'topMiddle',
                 tooltip: 'bottomMiddle'
              }
            }
    };

    $('form.uniForm input,form.uniForm textarea,form.uniForm select').each(function() {
       var nO = options;
       var hint = $(this).next('p.formHint');
       if(this.name == 'recaptcha_response_field' && $('#captchaHint').length) {
           nO.content = $('#captchaHint').text();
           $('#captchaHint').remove();
           $('#recaptcha_response_field').parents('div.ctrlHolder').qtip(nO);
       }else if(true == hint.length) {
           nO.content = hint.html();
           hint.remove();
           $(this).qtip(nO);
       }else{
           var title = $(this).attr('title');

           if(title !== '') {
               nO.content = title;
               $(this).attr('title','');
               $(this).qtip(nO);
           }
       }      
    })

    $('select#paymentDown,select#paymentTerms,select#paymentFrequency').change(function() {
        var data = {
            paymentDown: $('select#paymentDown').val(),
            paymentTerms: $('select#paymentTerms').val(),
            paymentFrequency: $('select#paymentFrequency').val(),
            invoice: $('input#invoice').val()
        };

        $('#paymentBreakDown').html('&nbsp;').addClass('loading');

        $.getJSON('/checkout/paymentplan/',data,function(data) {
            $('#paymentBreakDown').removeClass('loading').html(data.paymentPlan);
            $('p#gst').text('$'+data.gst);
            $('p#fee').text('$'+data.fee);
            $('p#total').text('$'+data.total);
            $('#paymentPlanCode').val('');
            $('#codeError').hide();
            $('#proceed-to-step-2').attr('value','Verify Code').attr('disabled','disabled');
        });
    });

    $('input[type=button]#proceed-to-step-2').live('click',function() {
        var e = this;

        var getData = {
            paymentDown: $('select#paymentDown').val(),
            paymentTerms: $('select#paymentTerms').val(),
            paymentFrequency: $('select#paymentFrequency').val(),
            invoice: $('input#invoice').val(),
            code:$('#paymentPlanCode').val()
        };

        $('.loading.paymentplan').show();
        $('#codeError').hide();

        $.getJSON('/checkout/verifycode/',getData,function(data){
            $('.loading.paymentplan').hide();
            if(data.verified)
            {
                 if ($(e).attr('value') != 'Generate')
                 {
                     $(e).attr('value', 'Generate');
                 } else {
                    if (confirm('Generating the payment plan, cannot be undone. Please confirm to continue'))
                    {
                        $(e).attr('disabled', 'disabled');
                        $('form#paymentPlanForm').submit();
                    }
                }
            }else{
                $('#codeError').show('pulsate', { times:1 }, 2000);
            }            
        });
    });
});

$(function() {
$('select#backorderPerPage,select#auctionPerPage').change(function(){
  $(this).parent('form').submit();
});

if ($('#filter').children().length)
{
   $('#filter').show();
}

});


(function($){
    $.fn.printElement = function(options){
        var mainOptions = $.extend({}, $.fn.printElement.defaults, options);
        //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
        //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
        if (mainOptions.printMode == 'iframe') {
            if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
                mainOptions.printMode = 'popup';
        }
        //Remove previously printed iframe if exists
        $("[id^='printElement_']").remove();

        return this.each(function(){
            //Support Metadata Plug-in if available
            var opts = $.meta ? $.extend({}, mainOptions, $this.data()) : mainOptions;
            _printElement($(this), opts);
        });
    };
    $.fn.printElement.defaults = {
        printMode: 'iframe', //Usage : iframe / popup
        pageTitle: '', //Print Page Title
        overrideElementCSS: null,
        /* Can be one of the following 3 options:
         * 1 : boolean (pass true for stripping all css linked)
         * 2 : array of $.fn.printElement.cssElement (s)
         * 3 : array of strings with paths to alternate css files (optimized for print)
         */
        printBodyOptions: {
            styleToAdd: 'padding:10px;margin:10px;', //style attributes to add to the body of print document
            classNameToAdd: '' //css class to add to the body of print document
        },
        leaveOpen: false, // in case of popup, leave the print page open or not
        iframeElementOptions: {
            styleToAdd: 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
            classNameToAdd: '' //css class to add to the iframe element
        }
    };
    $.fn.printElement.cssElement = {
        href: '',
        media: ''
    };
    function _printElement(element, opts){
        //Create markup to be printed
        var html = _getMarkup(element, opts);

        var popupOrIframe = null;
        var documentToWriteTo = null;
        if (opts.printMode.toLowerCase() == 'popup') {
            popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
            documentToWriteTo = popupOrIframe.document;
        }
        else {
            //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
            var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
            //Native creation of the element is faster..
            var iframe = document.createElement('IFRAME');
            $(iframe).attr({
                style: opts.iframeElementOptions.styleToAdd,
                id: printElementID,
                className: opts.iframeElementOptions.classNameToAdd,
                frameBorder: 0,
                scrolling: 'no',
                src: 'about:blank'
            });
            document.body.appendChild(iframe);
            documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
            if (documentToWriteTo.document)
                documentToWriteTo = documentToWriteTo.document;
            iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
            popupOrIframe = iframe.contentWindow || iframe;
        }
        focus();
        documentToWriteTo.open();
        documentToWriteTo.write(html);
        documentToWriteTo.close();
        _callPrint(popupOrIframe);
    };

    function _callPrint(element){
        if (element && element.printPage)
            element.printPage();
        else
            setTimeout(function(){
                _callPrint(element);
            }, 50);
    }

    function _getElementHTMLIncludingFormElements(element){
        var $element = $(element);
        //Radiobuttons and checkboxes
        $(":checked", $element).each(function(){
            this.setAttribute('checked', 'checked');
        });
        //simple text inputs
        $("input[type='text']", $element).each(function(){
            this.setAttribute('value', $(this).val());
        });
        $("select", $element).each(function(){
            var $select = $(this);
            $("option", $select).each(function(){
                if ($select.val() == $(this).val())
                    this.setAttribute('selected', 'selected');
            });
        });
        $("textarea", $element).each(function(){
            //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
            var value = $(this).attr('value');
            if ($.browser.mozilla)
                this.firstChild.textContent = value;
            else
                this.innerHTML = value;
        });
        var elementHtml = $element.html();
        return elementHtml;
    }

    function _getBaseHref(){
        return window.location.protocol + window.location.hostname + window.location.pathname;
    }

    function _getMarkup(element, opts){
        var $element = $(element);
        var elementHtml = _getElementHTMLIncludingFormElements(element);

        var html = new Array();
        html.push('<html><head><title>' + opts.pageTitle + '</title>');
        if (opts.overrideElementCSS) {
            if (opts.overrideElementCSS.length > 0) {
                for (var x = 0; x < opts.overrideElementCSS.length; x++) {
                    var current = opts.overrideElementCSS[x];
                    if (typeof(current) == 'string')
                        html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
                    else
                        html.push('<link type="text/css" rel="stylesheet" href="' + current.href + '" media="' + current.media + '" >');
                }
            }
        }
        else {
            $(document).find("link").filter(function(){
                return $(this).attr("rel").toLowerCase() == "stylesheet";
            }).each(function(){
                html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
            });
        }
        //Ensure that relative links work
        html.push('<base href="' + _getBaseHref() + '" />');
        html.push('</head><body style="' + opts.printBodyOptions.styleToAdd + '" class="' + opts.printBodyOptions.classNameToAdd + '">');
        html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
        html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts.leaveOpen && opts.printMode.toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
        html.push('</body></html>');

        return html.join('');
    };
    })(jQuery);

