FastInit.addOnLoad(function() {

    if($('banner-carousel') != undefined) {

        oMySlides = new iSlideShow({	
            start:0,	 	
            wait:6000,
            duration:0.9,
            slideDiv: 'banner-carousel'
        });

        oMySlides.startSlideShow();
    }

});


FastInit.addOnLoad(function() {
initCarousel();
});

FastInit.addOnLoad(function() {
//    Cufon.replace('div.p-box h4');
//    Cufon.replace('div.p-middle-bannerfloats span.title');
});


//setup page elements as required
Array.prototype.getUnique = function(GroupBy) {
    var o = {}, i, l = this.length, r = [];
    for(i=0; i<l; i++) o[this[i][GroupBy]] = this[i][GroupBy];
    for(i in o) r.push(o[i]);
    return r;
};

Array.prototype.grepObjects = function( field, test ) {
    var matches = [];
    for(var i = 0; i < this.length; i++ ) {
        if ((test.test && test.test(this[i])) || this[i][field] === test ) {
            matches.push(i);
        }
    }
    return matches;
};

document.observe("rates:loaded", function(e) { forexTips(); });

function getRadioValue(idOrName) {
        var value = null;
        var element = document.getElementById(idOrName);
        var radioGroupName = null;  
        
        // if null, then the id must be the radio group name
        if (element == null) {
                radioGroupName = idOrName;
        } else {
                radioGroupName = element.name;     
        }
        if (radioGroupName == null) {
                return null;
        }
        var radios = document.getElementsByTagName('input');
        for (var i=0; i<radios.length; i++) {
                var input = radios[ i ];    
                if (input.type == 'radio' && input.name == radioGroupName && input.checked) {                          
                        value = input.value;
                        break;
                }
        }
        return value;
}

                //stem:  null,
                //hook: null,



function forexTips() {
    $$('span[class*="forex"]').each(function(e) {

        if( ! $(e).hasClassName('initialized')) {

            var v = $(e).innerHTML;
            v = v.replace(/\D/g, '');
        
            //$(e).innerHTML = ((parseInt(v) == 0) ? '---' : commify(v));
    
            
            new Tip ($(e), forexContent( $(e) ), {
                style: "forex",
                viewport: true,
                hook: false,
                offset: { x: 5, y: 5 },
                width: 230,
                title: ((parseInt(v) == 0) ? '' : $(e).innerHTML + ' Japanese Yen = approx.' )
                })
    
    
            if( $(e).hasClassName('infoIcon') ) {
                $(e).update( $(e).innerHTML + "<sup><img class='infoicon' src='/graphics/infoicon.png' height='10' width='20' ></sup>");
                }
        
            $(e).addClassName('initialized');
        }
        
        });
}

function forexContent(e) {

    value = $(e).innerHTML.replace(/\D/gi,"");
    value = ((isNaN(value)) ? 0 : value);

    if(value == 0) {
        return '<div style="margin: 5px;"><b>Not available</b></div>';
        }

    var rowTemplate = new Template('<tr class="#{cssClass}"><td>#{currency}</td><td class="right">#{value}</td></tr>')

    var text = '';

    try {
         if (countryInfo.currencyCode) { var currencyCode = countryInfo.currencyCode }
        } catch(err) {
            var currencyCode = null;
    }

    
    if(! exchangeRates.rates.find(function(rate) {return (rate.currCode == currencyCode);}) ) {currencyCode = null;};

    var currencyList = exchangeRates.rates.findAll(function(rate) {return rate.currCode.match(/(USD|EUR)/); });       
    
    var re = new RegExp(currencyCode);
    currencyList = currencyList.concat( (exchangeRates.rates.findAll(function(rate) {return rate.currCode.match(re);} )) );
//    currencyList = currencyList.concat( (exchangeRates.rates.findAll(function(rate) {return ((currencyCode) ? (rate.currCode == currencyCode) : rate);})) );

    currencyList = currencyList.uniq();
    
    for (var i = 0, len = currencyList.length; i < len; i++) {
           
        var forex = (value / currencyList[i].exchRate);
        var decimals = 2;
        text = text + rowTemplate.evaluate({
            cssClass:   ((i % 2) ? 'roweven' : 'rowodd') + ' ' + (( (currencyList[i].currCode == currencyCode) && (len > 1)) ? 'highlight' : ''), 
            currency: currencyList[i].currName, 
            value: commify(forex.toFixed(decimals))
            });
    }

    return '<table class="currencyExch"><thead></thead><tbody>' + text + '</tbody><tfoot><tr><td colspan="2" style="font-size: .80em;"><b>For reference purposes only.</b><br>Your actual exchange rate will be determined by your payment processor.</td></tr></tfoot></table>';
}

function commify(num) {
    var numStr = num.toString();
    var a = Array();
    
    try {
        a = numStr.split('.');
    } catch(err) {
        a[0] = numStr;
        a[1] = ' ';
        }
    
     // simplify by only accepting integers longer than 3 digits
     if ( a[0].match(/\D/) || num.length < 3 ) return numStr;
    
    num = a[0].split('');
    num.reverse();
    numStr = num.join('');
    
     numStr = numStr.replace(/(\d\d\d)/g, "$1_marker_");
    
    // if we did one too many, take it back
    numStr = numStr.replace(/_marker_$/g, '');
    // replace the thousandth _marker_ with ',' or '.'
    numStr = numStr.replace(/_marker_/g, ',');
    
    num = numStr.split('');
    num.reverse();
    return num.join('') + ((typeof(a[1]) != "undefined") ? '.' + a[1] : '');
}

//document.observe('dom:loaded', function() {

function initCarousel() {

if( $('carousel-content') !== null ) {

   	var slides = $('carousel-content').childElements('div.slide');

   	 if (slides.length > 0) {
   	 	//set the banner display pane to the user settings
   	 	$('wrapper').setStyle({
   	 			width: slideshow.width + 'px',
   	 			height: slideshow.height + 'px'
   	 	});
   	 	$('carousel-wrapper').setStyle({
   	 			width: slideshow.width + 'px',
   	 			height: slideshow.height + 'px'
   	 	});
   	 	$('carousel-content').setStyle({
   	 			width: slideshow.width + 'px',
   	 			height: slideshow.height + 'px'
   	 	});
 
 //navigation or not
		if (slideshow.showControls) {
			//set nav style
			switch (slideshow.controlStyle) {
				case 'nav':
					$('leftrightNav').show();
					break;
				case 'jump':
					var jumpNav = $('jumpNav');
                    jumpNav.insert('<li><a href="javascript:" class="carousel-control" rel="prev">&laquo;</a></li>');
   					var i;
   					//generate the jump buttons
   					for (i = 1; i <= slides.length; i++) {
   						jumpNav.insert('<li><a href="javascript:" class="carousel-jumper" rel="slide-' + i + '">' + i + '</a></li>');
   					}
		            jumpNav.insert('<li><a href="javascript:" class="carousel-control" rel="next">&raquo;</a></li>');
//  					jumpNav.show();
		
					break;
				default:
//					$('leftrightNav').show();
					break;
				
			}
			//increase the outer wrapper to the user height plus the navigation
   	 		var wrapperHeight = $('navWrapper').getHeight() + $('wrapper').getHeight() - 2;
  	 	
			$('wrapper').setStyle({
   	 			width: slideshow.width + 'px',
   	 			height: wrapperHeight + 'px'
   	 		});
   	 		//finally display the navigation
			$('navWrapper').show();
 		} 
//      	$('wrapper').show();

		//make the carousel
      	new Carousel('carousel-wrapper', $$('#carousel-content .slide'), $$('a.carousel-control', 'a.carousel-jumper'), {duration: slideshow.animationSpeed, effect: 'fade', auto: true, frequency: slideshow.displayTime});
       
     } else {
     	$('wrapper').hide();
     }
     
}


}

//Event.observe(window, 'load', initCarousel, false);


FastInit.addOnLoad(function() {
///scripts/currencyRates

    new Ajax.Request('/rates/rates.txt',
        {   method: 'get',
            evalJS: 'false',
            onSuccess: function(request) { 
                try {
                    exchangeRates = request.responseText.evalJSON();
                    document.fire("rates:loaded"); 
                    } catch(err) { }
                }
        });

    //setup a standard fader
    if(! $('divFader')) {
        var divFader = new Element('div', {id: 'divFader'} ).hide();
        divFader.setStyle( {
            //display: 'none', 
            position: 'absolute', 
            top: '0px', 
            left: '0px', 
            width: '100%', 
            height: '100%', 
            backgroundColor: 'black', 
            opacity: '.50'
            });
        document.body.appendChild(divFader);
        Element.extend(divFader);
    }

//     try {
//         $$('table.itemlist').each(function(e) { $(e).observe('mousedown', prod_click_table.bindAsEventListener(this) ) });
//     } catch(err) { if(window.console) {console.log(err);} }
    
    //setup rollovers and allow divs to be clickable in IE
    $$('.itemlist tbody tr.rollover', 'div.rollover').each(function(e) {
        var x = $w( $(e).className).grep(/^productId/);
        var productInfo = x[0].split(":");
    
        if(productInfo[1]) {
            $(e).setStyle( {cursor: 'hand'} );    
//             try {
//                 $(e).observe('click', function(e) { parent.location = '/product/' + productInfo[1]; return false; }); 
//             } 
//            catch(err) {}

            try {
//                $(e).observe('click', prod_click.bindAsEventListener(this) );
                $(e).observe('mousemove', prod_rollover.bindAsEventListener(this) );
                $(e).observe('mouseout', clearpop.bindAsEventListener(this) );
            } catch(err) {}
        }

    }
    );

//setup the product info popups
        $$('a.prodRollover').each(function(element) {
    
            var relAttr = element.readAttribute('rel');
    
                new Tip ($(element), {
                    ajax: {
                        url: '/prod_rollover/' + relAttr,
                        options: {
                            method: 'get'
                            }
                        },
                    style: "forex",
                    viewport: true,
                    hook: false,
                    width: 352,
                    height: 187,
                    border: 1,
                    target: $(element).up('li')
                    })

        });

    $$('a.popup').each(function(e) {
        $(e).target = '_blank';
        $(e).onclick = function() { 
            return hs.htmlExpand(this, popupOptions);
            };
        }
    );


    //init TableKit basics
    TableKit.options.rowEvenClass = 'roweven';
    TableKit.options.rowOddClass = 'rowodd';

    TableKit.Sortable.addSortType(
        new TableKit.Sortable.Type('commified', {
        normal: function(v) {
            v = parseFloat(v.replace(/,/g, ''));
            return isNaN(v) ? 0 : v;
            }
        }),
        new TableKit.Sortable.Type('stockstatus', {
        normal: function(v) {
            v = v.replace(/\s/g, '').toLowerCase();
            switch(v) {
                case 'instock':
                    return 0;
                case 'lowstock':
                    return 1;
                case 'backordered':
                    return 3;
                case 'orderstop':
                    return 5;
                case 'futurerelease':
                    return 7;
                case 'outofstock':
                    return 103;
                case 'discontinued':
                    return 500;
                default:
                    return 100;
                }
            }
        })
    );

//end of init function 
    }
);

//display a video
//adds in a div to put in content and calls popup
function playVideo(args) {

    args.height = args.height || 365;
    args.width = args.width || 640;

    hs.outlineType = null;
    hs.wrapperClassName = 'colored-border';
    hs.height = args.height;
    hs.width = args.width;
    hs.preserveContent = false;

    var currentDate = new Date();
    var timestamp = currentDate.getMilliseconds();

    //setup a standard div to hold the content
    if(! $('videoPop')) {
        var divVideo = new Element('div', {id: 'videoPop' + timestamp} ).hide();
        document.body.appendChild( $(divVideo) );
        //Element.extend( $(divVideo) );
    }

    var strx = QT_GenerateOBJECTText(args.videoName, args.width, args.height, '','align','left','bgcolor', 'black','autoplay','true','target','self','controller','true');
    
    $('videoPop' + timestamp ).update(strx);
    
    //alert(strx);
    //$('videoPop').innerHTML = strx;

    var v = hs.htmlExpand(null, {contentId: 'videoPop' + timestamp, preserveContent: false });
    
    return false;

}

//allows clicking of containers
function prod_click_table(event) 
{
    var elt = $(Event.element(event));

//if(window.console) { console.log(elt) };

    //are we already on the container?    
    if(! elt.hasClassName('rollover')) {
        elt = elt.up('.rollover'); 
        event.stop();
    }
    else
    {
        return true;
        }

    
    var productInfo = $w(elt.className).grep(/^productId/)[0].split("\:")

    if(! productInfo[1]) {
        return false;
        }

    var location = '/product/' + productInfo[1];
 
    if(Event.isLeftClick(event)) {
        parent.location = location; 
    }
   
   
    return false; 
}    



