function bgColorShift(color) {
    $("body").animate({backgroundColor: color}, 1000)
}

function round_ie(selector) {
    $(selector).each(function(index) {
       var buttonClass = 'funky';
       var buttonText = $(this).text();
       var buttonHeight = $(this).height();
       var buttonWidth = $(this).width();
       if(buttonWidth == 0) {
           var characterCount = buttonText.length;
           buttonWidth = characterCount * 7;
       }
       var buttonColor = $(this).css('backgroundColor');
       if(buttonColor == '#454545') {
           if(buttonHeight > 12) {
               buttonClass = 'funkyGreyTall';
           } else {
               buttonClass = 'funkyGrey';
           }
       } else if(buttonColor == '#fff') {
           if(buttonHeight > 12) {
               buttonClass = 'funkyAltTall';
           } else {
               buttonClass = 'funkyAlt';
           }
       } else {
           if(buttonHeight > 12) {
               buttonClass = 'funkyTall';
           }
       }
       $(this).width(buttonWidth);
       $(this).empty();
       $(this).addClass(buttonClass).append('<span>' + buttonText + '</span>');
       $(this).removeClass('button').removeClass('alt');
    });
}
function deactivate() {return false;}
$(function() {
   if ($.browser.msie) {
       round_ie('.button, p.compare a');
   }
   
   if (typeof(swfobject)!='undefined' && typeof(swfFilePath)!='undefined') {
	swfobject.embedSWF(swfFilePath, "main-content",
	    "970", "377", "10.0.0", "", flashvars,
	    {wmode:'transparent',
	     menu:'false',
	     base: (typeof(requsetURI)!='undefined'?requsetURI:document.URL)});
    }

    // Temporary hack before ATG code changes
    if (document.location.pathname.substr(1,5)=="en_CA") {
	$('#country-language a').live('click', function(event){
	    event.preventDefault();
	    changeLanguage('fr');
	    });
    }

    if (document.location.pathname.substr(1,5)=="fr_CA") {
	$('#country-language a').live('click', function(event){
	    event.preventDefault();
	    changeLanguage('en');
	    });
    }
    // end hack
	    
    // Another hack to remove Support and Downloads tab for CA search results
    if (document.location.pathname.match(/^\/CA\/(en|fr)\/search\//)) {
	$('#pd-tab-nav-global li:nth-child(5)').remove();
    }   
    // end hack
  			   
    $("input.empty")
        .focus(function() {
        	if(!$(this).attr('defaultval')) $(this).attr('defaultval',$(this).val());
        	$(this).attr("lastval",$(this).val());
        	if(!$(this).attr("haschanged")||$(this).attr('haschanged')=="false") $(this).val("");
        })
        .blur(function(){
        	if($(this).val()!=""&&$(this).val()!=$(this).attr('defaultval')) {
        		$(this).attr("haschanged","true");
            }
        	if($(this).val()==""||$(this).val()==$(this).attr('defaultval'))  {
        		$(this).val($(this).attr('defaultval'));
        		$(this).attr('haschanged',"false");
        	}
            
        });
	
	 $("input.inktoner")
        .focus(function() {
            $(this).attr("lastVal",$(this).val());
            $(this).val("");
      //disableEnable3();
        })
        .blur(function(){
            if($(this).val()=="") {
                $(this).val($(this).attr("lastVal"));
         //disableEnable4($(this).attr("lastVal"));
            }
        });

	 $("input.homepage")
        .focus(function() {
            $(this).attr("lastVal",$(this).val());
            $(this).val("");
      //disableEnable5();
        })
        .blur(function(){
            if($(this).val()=="") {
                $(this).val($(this).attr("lastVal"));
         //disableEnable6($(this).attr("lastVal"));
            }
        });

     	
    $("#signup-form input.footer-text")
        .blur(function(){
            if($(this).val()=="" || $(this).val()==$(this).attr('defaultval')) {
                $(this).val("");
            }
        });

    $("#signMeUp").click(function(e) {
	e.preventDefault();
	var url = $(this).attr('href');
	var email = $('#signup-form #email').val();
	if (/([\w\-]+\@[\w\-]+\.[\w\-]+)/.test(email)) {
		$(e.target).closest("form").submit();
	} else {
	    $('#signup-form #email').addClass('inError');
	}
    });
    
    $('.default-address,.custom-dropdown, .default-payment').click(function() {
        if($(this).hasClass('open')) {
            $(this).removeClass('open').find('ul').hide();
        } else {
            $('.open').removeClass('open').find('ul').hide();
            $(this).addClass('open').find('ul').show().click(function(e) {e.stopPropagation();});
        }
    });
     
    
    $("body").click(function(){
        $("#navlist").slideUp(100,function(){
            $(this).addClass('closed');
        });
    });
    $('.print').click(function() {
        window.print();
        return false;
    });
	
    $('.blank').click(function(){
        var url = $(this).attr("href");
        window.open(url);
        return false;
    });
	$("#listImg, #inputBox").click(function(){
		if( $('#navlist').hasClass('closed')){
			$('#navlist').slideDown(100, function(){
                $(this).removeClass('closed');
            });
        } else {
			$('#navlist').slideUp(100, function() {
				$(this).addClass('closed')
			});
		}
        return false;
	});
    $("#navlist li").click(function(){
            var temp = $(this).text();
            $("#inputBox p").empty();
            $("#inputBox p").append(temp);
        });

	$('p.compare input[type="checkbox"]').removeAttr('checked');
	
    $('p.compare a.disabled').bind('click',deactivate);
    var t,a,g;
    t = null;
    g = false;
    $(".compare input:checkbox").click(function() {
		var compareName = $(this).attr('name');
		var tabVal = compareName.substring(7);
        var _h = $(document).scrollTop() + 50;
        var l = $(".compare input:checked").length;
        if(l>=2) { $('p.compare a').removeClass('disabled').unbind('click',deactivate); }
        else { $('p.compare a').addClass('disabled').bind('click',deactivate); }
        if(l==4) { // added lexmark specific jsp url to include pop up.
            a = siteURLAppender + '/catalog/category/includes/modal_proceed.jsp?modal=true&width=350&height=150&tabValue='+tabVal;
            tb_show(t,a,g,_h);
        } else if(l>4) { // added lexmark specific jsp url to include pop up.
            a = siteURLAppender + '/catalog/category/includes/modal_count.jsp?modal=true&width=450&height=150&tabValue='+tabVal;
            tb_show(t,a,g,_h);
            return false;
        }
    });

    $('.check-all').click(function() {
        $("#comparison input:checkbox").attr('checked',true);
        return false;
    });
    $('.check-none').click(function() {
        $("#comparison input:checkbox").attr('checked',false);
        return false;
    });

    $(".compare-select input:checkbox").click(function() {
        var l = $(".compare-select input:checked").length;
        var _h = $(document).scrollTop() + 50;
        if(l>=1) $('p.compare a').removeClass('disabled').unbind('click',deactivate);
        else $('p.compare a').addClass('disabled').bind('click',deactivate);
        if(l==3) { // added lexmark specific jsp url to include pop up.
            a = siteURLAppender + '/catalog/product/printerinclude/modal_proceed.jsp?modal=true&width=350&height=150';
            tb_show(t,a,g,_h);
            return true;
        } else if(l>3) { // added lexmark specific jsp url to include pop up.
            a = siteURLAppender + '/catalog/product/printerinclude/modal_count.jsp?modal=true&width=450&height=150';
            tb_show(t,a,g,_h);
            return false;
        } else {return true;}
    });
    $('.awards-view').click(function(){
        $('#tab-awards-action').click();
        return false;
    });
    var cartTimer; // setting var in global space for the next 2 functions
    $('#cart-ul').mouseenter(function(){
        var _this = $(this);
        cartTimer = setTimeout(function(e){
        if(!_this.hasClass('open-cart')) {
            _this.addClass('open-cart');
            $.get(_this.find('a').attr('rel'),function(cart){
                $('#mini-cart').css({
                    'top':_this.height()-7
                }).html(cart).show();
                if ($.browser.msie) { round_ie('#mini-cart .button'); }
                if ($.browser.msie && $.browser.version == '6.0') $('#mini-cart').css({overflow:'hidden'}).append($('<iframe></iframe>').css({position:'absolute',width:'400px',height:'500px',border:'1px solid red',top:0,left:0,zIndex: -1}));
            });
        }
        },500);
    });
    $('#cart-ul').mouseleave(function(){
        clearTimeout(cartTimer);
        var _this = $(this);
        if(_this.hasClass('open-cart')) {
            _this.removeClass('open-cart');
            $('#mini-cart').hide().empty();
        }
    });

    $('.shopping-cart input.quantity-box').each(function(){
        var _i = $(this);
        var _a = _i.parent().find('a.funkyAlt');
        _i.bind('change', function(event){
            shopping_cart_deactivate_add_to_cart(_i,_a)
        });
    });
   var $countrySpan = $('#header-selectbox .country-label').width();
    var $countryFlag = $('#header-selectbox .country-flag').width();
    var $countryWidth = $countrySpan + $countryFlag + 45;
    $('#header-selectbox').width($countryWidth);
    var $languagePosition = $countryWidth + 210;
    if($('html').attr('dir') == 'rtl') {
        $('#country-language').css({left: 'auto', right: $languagePosition});
    } else {
        $('#country-language').css({left: $languagePosition, right: 'auto'});
    }
    var calloutWidth = $('#signup-form .callout').width() + 1;
    var emailWidth = $('#signup-form .email-form .round-input').outerWidth() + $('#signup-form .email-form a').outerWidth() + 10;
    $('#signup-form .callout').css('width', calloutWidth);
    $('#signup-form .email-form').css('width', emailWidth);

	if($('.compare-height').length != -1){compareHeight();}
	if($('#shop-ink-toner').length != -1){matchHeight($(this), '.matchIt');}


	$('form.search-box input[type="text"]').each(function() {
             var searchBox = $(this);
            var sbStart = "3"
            var sbWidth = searchBox.innerWidth();
            sbWidth = sbWidth + 12;
			var currentCount = 0;
			searchBox.keyup(function() {
				if (searchBox.val().length < 2)
				{
					return;
				}
				if (currentCount < 1)
				{
					currentCount++;
				//url="/products/home/includes/inkAndTonerSearchSuggest.jsp?searchterm=" + escape(searchBox.val());
				url= siteURLAppender + "/home/includes/inkAndTonerSearchSuggest.jsp";
				searchBox.autocomplete(url, { matchContains: true, max: 15, minChars: sbStart, scroll: false, width: sbWidth});
				}
			});
	});
	
    // Dynamic Country dropdown list handling
    var countryLayer = $('#countrylayer'),
            countryLink = $('a.country-link'),
            selectBox = $('#header-selectbox'),
            countryWrapper = $('a.country-link .country-wrapper');

    selectBox.click(function(){

        // hide country select if visible
        if (countryLayer.is(":visible")){
            countryLayer.hide();
            countryLink.removeAttr('style');
            countryWrapper.removeAttr('style');
        } 
        else {

            // TODO: Should toggle class not set explicit styles here!
            countryLink.css('background','url(/en_US/common/img/country-tab-long.gif) no-repeat scroll left top transparent');
            countryWrapper.css('background','url(/en_US/common/img/country-tab-long.gif) no-repeat scroll right top transparent');

            // load the list of countries if they are not already present in the DOM
            if ($("#countrylayer .content-column").length == 0) {
                countryLayer.load('/common/country-list.shtml?lang='+ window.location.pathname.substr(1,5), function(response, status, xhr) {
                    if (status == "success") {
                        // parse the response and find the number of countries being injected
                        var numberOfCountries = $(response).find('.content-column .content-list li').length;

                        // customize the drop down depending on number of countries
                        if (numberOfCountries !== null && numberOfCountries > 25) {
                            countryLayer.css({"position":"absolute","left": "-200px"});
                        }
                        if (numberOfCountries !== null && numberOfCountries <= 25) {
                            countryLayer.css({"position":"absolute","left": "-80px", "width": "250px"});
                        }
                    }
                });   
            }
            countryLayer.slideDown(200);   
        }
    });

    selectBox.mouseup(function(){ return false;});
    $(document).mouseup(function() {
        if (countryLayer.is(":visible")){
            countryLayer.hide();
            countryLink.removeAttr('style');
            countryWrapper.removeAttr('style');
        }
    });
    // End dynamic country dropdown.
});

function home_modal_deactivate_add_to_cart() {
    var _a = $('.added-cart .related-products~.page-action a').remove();
    var _span = $('<span class="'+ _a.attr('class') + '" style="' + _a.attr('style') + '">'+_a.html()+'</span>').appendTo('.added-cart .related-products~.page-action');
    $(".added-cart .related-products input:checkbox").click(function() {
        var l = $(".added-cart .related-products input:checked").length;
        if(l>=1) {
            _span.remove();
            _a.appendTo('.added-cart .related-products~.page-action');
        }
        else {
            _a.remove();
            _span.appendTo('.added-cart .related-products~.page-action');
        }
    });
}

function shopping_cart_deactivate_add_to_cart(_i, _a) {
    var _newspan = $('<span class="funkyAlt"><span>'+_a.text()+'</span></span>');
    if (_i.val().length < 1) {
        _a.remove();
        _newspan.insertAfter(_i).css({marginLeft:'3px'});
    } else {
        if (_i.parent().find('span.funkyAlt').length > 0) {
            _i.parent().find('span.funkyAlt').remove();
            _a.insertAfter(_i).css({marginLeft:'3px'});
        }
    }
}

function compareHeight(){ // compare the height of ".info-wrapper" elements in any ".compare-height".
	$('.compare-height').each(function(){
		var arr = [];
		var _length = $(this).find('.info-container').length;
		for(var i = 0; i < _length; i ++ ){
			arr.push($(this).find('.info-container').eq(i).height());
		}
		var maxHeight = Math.max.apply(Math, arr);
		$(this).find('.info-container').each(function(){
			if($(this).height() < maxHeight){
//				alert(maxHeight + ',' + $(this).height());
				var newHeight = $(this).find('.info-wrapper').height() + (maxHeight - $(this).height());
				$(this).find('.info-wrapper').height(newHeight);
			}
			
			
		});
	});
}

function matchHeight(that, element){
	var arr = [];
	var _length = that.find(element).length;
	
	for(var i = 0; i < _length; i ++ ){
	    arr.push(that.find(element).eq(i).height());
	}
	
	var maxHeight = Math.max.apply(Math, arr);
	that.find(element).each(function(){
	    if($(this).height() < maxHeight){
		$(this).height(maxHeight);
	    }
	});
}

$(function() {
    $('a.modal').click(function() {
        window.swfobjectXhrQueryString = this.href.replace(/^[^\?]+\??/, '');
    });
});


