//global init
jQuery.preloadImages = function() {
    for (var i = 0; i < arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

function BrowserCheck() {
    var agent = navigator.userAgent.toLowerCase();
    var ver = parseInt(navigator.appVersion);

    var ie = agent.indexOf("msie") >= 0;
    var ie6 = ie && agent.indexOf("msie 6") >= 0;
    var ie7 = ie && agent.indexOf("msie 7") >= 0;

    var ff = !ie && agent.indexOf("mozilla") >= 0;
    var ff2 = ff && ver == 4;
    var ff3 = ff && ver == 5;

    if (ff3) {

    } else if (ie6) {

    } else if (ie7) {
        //alert("ie7.2");
        if (typeof $j('ul.hoverMenu').bgiframe == 'function') {
            $j('ul.hoverMenu').bgiframe();
        }
    //    $j('.subMenu').bgiframe();
    //    $j('.menuitem').bgiframe();
    
    } else {

    }

}

$j(document).ready(
	function() {
        BrowserCheck();
	    if ($j('.tickerItem').size() > 0) {
	        // Init the news ticker if it exists
	        initNewsTicker()
	    }
	    
	    globalInit();
	    if ($j("#carouselRenderer").size() > 0) {
	        // init the carousel if it exists.	    
	        initCarousel();
	    }
	    if (!window.XMLHttpRequest) {
	        FixIE6PNG();
	    }
		
		$j('.infoBox').hover(function(){ 
            $j(this).parent().find('.infoBoxText').show('blind'); 
        }, function(){ 
            $j(this).parent().find('.infoBoxText').hide('blind'); 
        } 
		);

	    
	}
);
function globalInit() {
    replaceFonts();
    initMainMenu();
    initReflections();
    initLightbox();
}

//cufon font replacement
function replaceFonts() {
    Cufon.replace('.cufonBookHover', { hover: true, fontFamily: 'CanonBook' });
    Cufon.replace('.cufonBook', { fontFamily: 'CanonBook' });
    Cufon.replace('.cufonLightHover', { hover: true, fontFamily: 'CanonLight' });
    Cufon.replace('.cufonLight', { fontFamily: 'CanonLight' });
    Cufon.replace('.cufonBoldHover', { hover: true, fontFamily: 'CanonBold' });
    Cufon.replace('.cufonBold', { fontFamily: 'CanonBold' });
    Cufon.replace('.cufonMediumHover', { hover: true, fontFamily: 'CanonMedium' });
    Cufon.replace('.cufonMedium', { fontFamily: 'CanonMedium' });
    //cufonSite - site specific styling for shared components
    Cufon.replace('.cufonSite', { fontFamily: 'CanonBook' });
    Cufon.replace('.cufonSite2', { fontFamily: 'CanonLight' });
    $j('.cufonBookHover, .cufonLightHover, .cufonBoldHover, .cufonMediumHover').each(function() {
        $j(this).bind("click", function(e) {
            if ($j.browser.msie) {
                // Dirty IE Cufon hack, if you scroll off a cufon a element with the trident engine
                // it throws a javascript error, this catches the click, removes the offending
                // hover cufon vml, and then throws window.location to the original href. 
                Cufon.replace('.cufonBookHover', { fontFamily: 'CanonBook' });
                window.location = $j(this).attr('href');
            }
        });
    });
}

//font replacement for post-ajax call
function replaceFontsAgain() {
    Cufon.refresh();
}

function initNewsTicker() {

    var currentTickerItem = 0;
    var newsItems = $j('.tickerItem').size();
    $j('.tickerItem').each(function(i) {

        if (i > 0) $j(this).hide();

    });

    function nextTickerItem() {
        var currentItem = $j('.tickerItem:nth-child(' + currentTickerItem + ')');
        currentTickerItem++;
        if (currentTickerItem == newsItems) {
            currentTickerItem = 0;
        }
        var nextItem = $j('.tickerItem:nth-child(' + currentTickerItem + ')');
        currentItem.slideUp("medium", function() {
            nextItem.slideDown("medium");
        });
    }
    setInterval(nextTickerItem, 10000)
    $j("#newsItems").css({
        "display": "block"
    });
}

//main menu drop down
function initMainMenu() {
    $j('ul.hoverMenu > li').hover(function() {
        var underlineWidth = $j(this).outerWidth();
        var underlineDiv = $j('#headerMenu ul ul li.first');
        underlineDiv.html('<div style="width: ' + String(underlineWidth - 2) + 'px; height: 1px; margin-left: 14px;"></div>\n' +
													'<div style="width: ' + String(underlineWidth) + 'px; height: 1px; margin-left: 13px;"></div>\n');
        //													'<div style="height: 3px; width: 200px">');
        if ($j('ul > li', this).size() == 2) {
            $j('ul > li.last', this).hide();
        }
        $j('ul', this).addClass('active');
        if (!window.XMLHttpRequest) {
            // IE 6 underline + rounded corner bottom
            underlineDiv.html('<div style="width: ' + String(underlineWidth - 2) + 'px; height: 1px; margin-left: 14px;margin-top:-10px;"></div>\n');
            $j('.active li.last').each(function() {
                IEPNGFix.fix(this, "/images/mainMenuSubBottom.IE6.png", 2);
            });

        }
        $j('#header').addClass('menuActive');
        //transparency code here?
    }, function() {
        $j('ul', this).removeClass('active');
        $j('#header').removeClass('menuActive');
    });
}
// Arg[0] unordered list horiz strip param
function initCarousel(mainStrip) {
    if (!mainStrip) {
        var mainStrip = $j('#carouselRenderer');
    }

    var visibleItems = 4;
    // Get the width of the carousel based on the amount of items in the system, make it negative for comparison purposes.
    totalWidth = (mainStrip.children().size() * mainStrip.children().outerWidth() * -1)
    var totalImages = mainStrip.children().size();
    overflowedImages = totalImages - visibleItems;
    if (overflowedImages <= 0) {
        mainStrip.parent().siblings('#carouselRendererLeft').hide();
        mainStrip.parent().siblings('#carouselRendererRight').hide();
    } else {
        mainStrip.parent().siblings('#carouselRendererLeft').hide();
        mainStrip.parent().siblings('#carouselRendererRight').fadeIn(200);
    }
    var item_width = mainStrip.children().outerWidth();
    var currentPosition = 0;
    // Clear bindings
    mainStrip.parent().siblings('#carouselRendererRight').unbind();
    //move the last list item before the first item. The purpose of this is if the user clicks previous he will be able to see the last item.
    //$j('#carousel_ul li:first').before($j('#carousel_ul li:last'));
    //when user clicks the image for sliding right
    mainStrip.parent().siblings('#carouselRendererRight').click(function() {
        //get the width of the items ( i like making the jquery part dynamic, so if you change the width in the css you won't have o change it here too ) '

        //calculate the new left indent of the unordered list
        var left_indent = parseInt(mainStrip.css('left')) - item_width;

        //make the sliding effect using jquery's anumate function '
        if (totalImages - currentPosition > visibleItems && (parseInt(mainStrip.css('left')) % item_width) == 0) {
            mainStrip.animate({ 'left': left_indent }, { queue: false, duration: 500 }, function() {
                //get the first list item and put it after the last list item (that's how the infinite effects is made) '
            mainStrip.find('.carouselRendererItem:last').after(mainStrip.find('.carouselRendererItem:first'));

                //and get the left indent to the default -210px
                mainStrip.css({ 'left': '-210px' });
            });
            currentPosition++;
            mainStrip.parent().siblings('#carouselRendererLeft').show();
        }
        if (currentPosition + visibleItems == totalImages) {
            mainStrip.parent().siblings('#carouselRendererRight').hide();
        }
        if (currentPosition == 0) {
            mainStrip.parent().siblings('#carouselRendererLeft').hide();
        }
    });

    // Clear bindings
    mainStrip.parent().next('#carouselRendererLeft').unbind();
    //when user clicks the image for sliding left
    mainStrip.parent().next('#carouselRendererLeft').click(function() {

        /* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */
        var left_indent = parseInt(mainStrip.css('left')) + item_width;
        if (currentPosition != 0 && (parseInt(mainStrip.css('left')) % item_width) == 0) {
            mainStrip.animate({ 'left': left_indent }, { queue: false, duration: 500 }, function() {

                /* when sliding to left we are moving the last item before the first item */
                $j('.carouselRendererItem:first').before($j('.carouselRendererItem:last'));

                /* and again, when we make that change we are setting the left indent of our unordered list to the default -210px */
                mainStrip.css({ 'left': '-210px' });
            });
            currentPosition--;
            $j('#carouselRendererRight').show();
        }
        if (currentPosition + visibleItems == totalImages) {
            $j('#carouselRendererRight').hide();
        }
        if (currentPosition == 0) {
            $j('#carouselRendererLeft').hide();
        }
    });
}

function initReflections() {

    //carousel image reflections
    var reflectOptions = { height: "30px", opacity: 0.3 };
    //disabled as per discussions w/greg
    //$j('.carouselRendererItem img').reflect(reflectOptions);
}


// Functions for MyShelf and MyWishList
function removeThis(url) {
    var answer = confirm('Are you sure you want to remove this product?');
    if (!answer) return;
    location.href = url;
}

// Comp lightbox js

function getcomparer() {
    var i = 1;
    var str = "/Global/Compare?"
    var guids = [];

    $j("input[type='checkbox']").each(function() {
        if ($j(this).attr('checked')) {
            guids.push("prod" + i + "=" + $j(this).attr('value'));
            i++;
        }

    });
    $j('#comparisonLightboxBackdrop').fadeTo(1, 0.7, function() {
        $j('#comparisonLightbox').load(str + guids.join("&")).fadeIn(1);
    }).css('display', 'block');
}


function FixIE6PNG() {
    // Adam and Matt fixed this on the 12th March 2010... just in case some weird browser plugin returns the wrong answer on browser test.
    if (IEPNGFix) {
        $j(".carouselRendererItem img").each(function() {
            IEPNGFix.fix(this, $j(this).attr('src'), 2);
        });
    }
}

var fadevar = 300;

function showobject(name, url, fade) {
    if (fade) {
        $j.ajax({
            type: "GET",
            url: url,
            success: function(html) {
                $j(name).fadeOut(fadevar, function() {
                    $j(name).html(html);
                    replaceFontsAgain();
                    //if IE6 (pngfix js included) do pngfix on ajax content
                    if (window.IEPNGFix) {
                        $j(name + ' img.pngfix').each(function() {
                            IEPNGFix.fix(this, $j(this).attr('src'), 2);
                        });
                    }
                    //if autoHeight.js included in page, do iframe resize
                    $j(name).fadeIn(fadevar);
                    if (window.doIframe) {
                        doIframe();
                    }
                });
            }
        });
    } else {
        $j.ajax({
            type: "GET",
            url: url,
            success: function(html) {
                $j(name).html(html);
                replaceFontsAgain();

                $j(name + ' img').each(function() {

                    IEPNGFix.fix(this, $j(this).attr('src'), 2);

                });

            }
        });
    }
    return false;
}

function tabLinkApplyTab() {
    //'this' is the <a> inside an active tab
    var tabWidth = $j(this).outerWidth();
    if (!$j(this).get(0).tabSet) {
        if (window.XMLHttpRequest) {
            //most browsers
            $j(this).parent().append('<div  id="underlineStatusSelection" style="width: ' + tabWidth + 'px;">\n' +
															         '  <div style="margin-top:-24px;position: absolute; bottom: 0px; height: 4px; width: ' + tabWidth + 'px;">\n' +
															         '    <div style="margin: 0 4px; background-color: #cc0000;"></div>\n' +
															         '    <div style="margin: 0 2px; background-color: #cc0000;"></div>\n' +
															         '    <div style="margin: 0 1px; background-color: #cc0000;"></div>\n' +
															         '    <div style="margin: 0; background-color: #cc0000;"></div>\n' +
															         '  </div>\n' +
															         '</div>');
        } else {
            //older IEs
            $j(this).parent().append('<div style="left: -' + (tabWidth / 2) + ';height: 35px;  position: relative; width: ' + tabWidth + 'px;">\n' +
															         '  <div style="margin-top:-24px;position: absolute; bottom: 0px; height: 4px; width: ' + tabWidth + 'px; font-size:0px;">\n' +
															         '    <div style="margin: 0 4px; background-color: #cc0000; font-size:0px;"></div>\n' +
															         '    <div style="margin: 0 2px; background-color: #cc0000; font-size:0px;"></div>\n' +
															         '    <div style="margin: 0 1px; background-color: #cc0000; font-size:0px; "></div>\n' +
															         '    <div style="margin: 0; background-color: #cc0000; font-size:0px;"></div>\n' +
															         '  </div>\n' +
															         '</div>');
        }
        $j(this).get(0).tabSet = true;
    }

    //$j('.selectedProductText').parent().removeClass('active');
    //$j(this).parent().addClass('active');

    //$j('.selectedProductText').parent().css('background-color', 'rgb(237, 237, 237)');
}

function CallPrint(strid) {
    var prtContent = document.getElementById(strid);
    var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=600,t oolbar=0,scrollbars=0,status=0');
    WinPrint.document.write("<html style='text-align: left;'>");
    WinPrint.document.write("<head><link type='text/css' rel='stylesheet' href='/css/canonForms.css' /><link type='text/css' rel='stylesheet' href='/css/canonGlobal.css' /><style>cufon{display: none;}</style></head><body style='text-align: left;'>");
    WinPrint.document.write("<img src='~/media/images/headerLogo.ashx'></img><br/><br/>");
    WinPrint.document.write(prtContent.innerHTML);
    WinPrint.document.write("</body></html>");
    WinPrint.document.close();
    WinPrint.focus();
    WinPrint.print();
    WinPrint.close();
}

function initLightbox() {
    setTimeout(function() {
        $j('#fancybox-wrap').prepend('<div id="fancybox-outer-top"></div>').append('<div id="fancybox-outer-bottom"></div>');
        $j('#sfancybox-title').addClass('cufonLight');
    }, 250);
}
