YAHOO.namespace('BWB');
YAHOO.BWB.productDetail = function() {
    
    var priv = {
        vid_panel:     null,
        img_panel:     null,
        currentItem:   null,
        currentReq:    null,
        loadingTicker: null,
        init: function() {
            var fin = document.getElementById('finishes'),
                selectedFinishes = YAHOO.util.Dom.getElementsByClassName('selected', 'li', fin);
            if(selectedFinishes) {
                priv.currentItem = selectedFinishes[0];
            }
            var flashLink = document.getElementById('flash_video');
            YAHOO.util.Event.on(flashLink,         'click',  priv.handleVideoPlay, priv, true);
            YAHOO.util.Event.on('finishes',        'click',  priv.handleFinishChange, priv, true);
            YAHOO.util.Event.on('product-form',    'change', priv.handleFinishChange, priv, true);
            YAHOO.util.Event.on('product-thumbs',  'click',  priv.handleThumbClick, priv, true);
            YAHOO.util.Event.on('main-image',      'click',  priv.handleImgZoom, priv, true);

            // create vid_panel:
            priv.vid_panel = new YAHOO.widget.Panel("vid-panel", {
                width:"420px",
                fixedcenter:true,
                close:true,
                draggable:false,
                zindex:800,
                modal:true,
                visible:false
            });  
            priv.vid_panel.setHeader("Furniture Video"); 
            priv.vid_panel.setBody('<img src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" />'); 
            priv.vid_panel.render(document.body);
            
            priv.img_panel =  new YAHOO.widget.Panel("img-panel", {
                width:"740px",
                height:"540px",
                fixedcenter:true,
                close:true,
                draggable:false,
                zindex:800,
                modal:true,
                visible:false
            });  
            priv.img_panel.setHeader("Furniture Detail Image"); 
            priv.img_panel.setBody('<img width="100%" src="http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif" />'); 
            priv.img_panel.render(document.body);
            
            priv.loadingTicker = document.createElement('div');
            priv.loadingTicker.className = 'ticker';
            
            priv.loadingTicker.innerHTML = '<div><img src="/static/images/ajax-loader.gif" alt=""> Loading...</div>';
            priv.loadingTicker.style.display = 'none';
            document.getElementById('product-images').appendChild(priv.loadingTicker);
        },
        handleFinishChange: function(e) {
            var targ = YAHOO.util.Event.getTarget(e),
                li = (targ.tagName.toUpperCase() == 'LI') ? targ : YAHOO.util.Dom.getAncestorByTagName(targ, 'li'),
                sel = priv.currentItem.getElementsByTagName('select');
            
            if(li) {
                    YAHOO.util.Dom.removeClass(priv.currentItem, 'selected');
                    YAHOO.util.Dom.addClass(li, 'selected');
                    var finishTypeArray = li.getElementsByTagName('input');
                    if(finishTypeArray && finishTypeArray[0]) {
                        finishTypeArray[0].checked = true;
                    }
                    
                    priv.currentItem = li;
                    priv.currentSpray = targ.value;
                    // call this here so we update on 
                    priv.handlePriceUpdate();
            }
        },
        handlePriceUpdate: function() {
            var prodForm = document.getElementById('product-form'),
                prodDetailId, prodFinishId, prodSprayId;
            if(prodForm) {

                prodDetailId = prodForm.product_detail_id.value;
                prodFinishId = (prodForm.finish_id && prodForm.finish_id.value) ? prodForm.finish_id.value: false;
                
                if(!prodFinishId) {
                    for(var i = 0, j = prodForm['finish_id'].length; i < j; i++) {
                        if(prodForm['finish_id'][i].checked) {
                            prodFinishId = prodForm['finish_id'][i].value;
                        }
                    }
                }
                prodSprayId  = (prodForm['spray_type_id_' + prodFinishId]) ? prodForm['spray_type_id_' + prodFinishId].value : 0;
                if(priv.currentReq) {
                    YAHOO.util.Connect.abort(priv.currentReq);
                }                                     
                priv.loadingTicker.style.display = 'block';
                priv.currentReq = YAHOO.util.Connect.asyncRequest('GET', '/index.php/sbf/getprice/' + prodDetailId + '/' + prodFinishId + '/' + prodSprayId, priv.callback);
                
            }
        },
        callback: {
            success: function(o) {
                var price = document.getElementById('pricetext'),
                    json = o.responseText.substring(o.responseText.indexOf('{'), o.responseText.lastIndexOf('}') + 1),
                    data = eval('(' + json + ')'),
                    imgs = data['imgs'],
                    thumbsEl = document.getElementById('product-thumbs'),
                    mainImgEl = document.getElementById('main-image'),
                    html = ''; 
                
                for(var i in imgs) {
                    html += '<li><img src="'+imgs[i]['small_url']+'" width="80" height="74"></li>';
                }
                
                var fadeOut = new YAHOO.util.Anim([price, thumbsEl, mainImgEl], { opacity: { to: 0 } }, 0.3, YAHOO.util.Easing.easeIn);
                var fadeIn = function(type, args) {
                    price.innerHTML = '&pound;' + data.price;
                    mainImgEl.src = imgs[0]['medium_url'];
                    thumbsEl.innerHTML = '<ol>'+html+'</ol>';
                    
                    var fadeIn = new YAHOO.util.Anim([price, thumbsEl, mainImgEl], { opacity: { to: 1 } }, 0.3, YAHOO.util.Easing.easeOut);
                    fadeIn.animate();
                    fadeIn.onComplete.subscribe(function(type, args) {
                        priv.currentReq = false;
                        priv.loadingTicker.style.display = 'none';
                    });
                };
                fadeOut.onComplete.subscribe(fadeIn);
                fadeOut.animate();
            }
        },
        handleThumbClick: function(e) {
            var targ = YAHOO.util.Event.getTarget(e),
                li = (targ.tagName.toUpperCase() == 'LI') ? targ : YAHOO.util.Dom.getAncestorByTagName(targ, 'li'),
                mainImg = document.getElementById('main-image');
            
            if(li) {
                var thumb = li.getElementsByTagName('IMG')[0],
                    thumbUrl = (thumb) ? thumb.src : false;
                
                if(priv.lastThumb) {
                    YAHOO.util.Dom.removeClass(thumb, 'selected');
                }
                priv.lastThumb = thumb;
                
                YAHOO.util.Dom.addClass(thumb, 'selected');
                thumbUrl = thumbUrl.replace('_small.','_medium.');
                mainImg.src = thumbUrl;
            }
        },
        handleVideoPlay: function(e) {
            YAHOO.util.Event.preventDefault(e);
            var targ = YAHOO.util.Event.getTarget(e);
            priv.vid_panel.setBody("<object width='400' height='325' id='flvPlayer'>"+
                  "<param name='allowFullScreen' value='false'>"+
                  "<param name='movie' value='/static/OSplayer.swf?movie="+targ.href+"&btncolor=0x333333&accentcolor=0x31b8e9&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=on&vTitle=Furniture Demonstration Video&showTitle=yes'>"+ 
                  "<embed src='/static/OSplayer.swf?movie="+targ.href+"&btncolor=0x333333&accentcolor=0x31b8e9&txtcolor=0xdddddd&volume=30&autoload=on&autoplay=on&vTitle=Furniture Demonstration Video&showTitle=yes' width='400' height='325' allowFullScreen='false' type='application/x-shockwave-flash'>"+ 
                 "</object>"
            );
            priv.vid_panel.show();
        },
        handleImgZoom: function(e) {
            YAHOO.util.Event.preventDefault(e);
            var targ = YAHOO.util.Event.getTarget(e),
                mainImgUrl = targ.src;
            mainImgUrl = mainImgUrl.replace('_medium.', '_large.');
            priv.img_panel.setBody('<img src="' + mainImgUrl + '"><a href="#" onclick="swapImage(thumbCount - 1);" id="imgPrev">Previous</a><a href="#" onclick="swapImage(thumbCount + 1);" id="imgNext">Next</a>');
            priv.img_panel.show();
            findCurrentImagePoint(); // this is finding the users current point in the lightbox
        }

    };
    
    var caro = {
        el: null,
        width: 0,
        itemWidth: 0,
        length: 0,
        currentPane: 0,
        inAnim: false,
        
        /* Init carousel */
        init: function(el) { // product-thumbs
            return;
            caro.el = YAHOO.util.Dom.get(el);
            caro.list = caro.el.getElementsByTagName('UL')[0];
            caro.items = caro.el.getElementsByTagName('LI');
            caro.width = parseInt(caro.el.offsetWidth);
            caro.itemWidth = parseInt(caro.items[0].offsetWidth);
            caro.length = caro.items.length;
            caro.maxPanes = Math.ceil((caro.itemWidth * caro.length)/caro.width);
            caro.buildNavigation();
        },
        
        prev: function(e) {
            YAHOO.util.Event.preventDefault(e);
            if(caro.currentPane != 0 && !caro.inAnim) {
                caro.move(-1);
            }
        },
        next: function(e) {
            YAHOO.util.Event.preventDefault(e);
            if(caro.currentPane != (caro.maxPanes - 1) && !caro.inAnim) {
                caro.move(1);
            }
        },
        move: function(dir) {
            caro.inAnim = true;
            var caroAnim = new YAHOO.util.Anim(caro.list, {
                    left: {
                        by: dir * caro.width 
                    } 
                }, 1, YAHOO.util.Easing.easeOut);
            caroAnim.onComplete.subscribe(function() {
                caro.inAnim = false;
                caro.currentPane += dir;
            });
            caroAnim.animate();
        },
        
        buildNavigation: function() {
            var wrapper = caro.el.parentNode,
                prevEl = caro.createButton('Previous', 'prev', caro.prev),
                nextEl = caro.createButton('Next', 'next', caro.next);
            wrapper.insertBefore(prevEl, caro.el);
            wrapper.appendChild(nextEl);
        },
        createButton: function(name, className, callback) {
            var button = document.createElement('button');
            button.innerHTML = name;
            button.className = className;
            YAHOO.util.Event.on(button, 'click', callback);
            return button;
        }
    };
    
    var pub = {
        init: function() {
            priv.init();
            caro.init('product-thumbs');
        }
    };
    return pub.init;    
    
}();

var thumbCount = 0;

function swapImage(e){
	document.getElementById("img-panel").getElementsByTagName("img")[0].src = stripURL(e);	
	findCurrentImagePoint();
}

function stripURL(i) {
	var imageURL = document.getElementById("product-thumbs").getElementsByTagName("img")[i].src.replace('_small.','_large.');
   	return imageURL;
}

function findCurrentImagePoint(){
	var mainImgUrl = document.getElementById("img-panel").getElementsByTagName("img")[0].src;
	var countThumbs = document.getElementById("product-thumbs").getElementsByTagName("li").length;
	
	for (var i = 0; i < countThumbs; i++) {
   		imageURL = stripURL(i);
   		if (imageURL == mainImgUrl){
   			thumbCount = i;
   		}
	}
	if (thumbCount == 0){
   		document.getElementById("imgPrev").style.display = "none";
   	}
   	else {
   		document.getElementById("imgPrev").style.display = "";
   	}
   	if (thumbCount == countThumbs - 1){
   		document.getElementById("imgNext").style.display = "none";
   	}
   	else {
   		document.getElementById("imgNext").style.display = "";
   	}
}


YAHOO.util.Event.onDOMReady(YAHOO.BWB.productDetail);

