var QUICK_LOOK_WIDTH = 721;
var QUICK_LOOK_HEIGHT = 518;
var AJAX_CART_WIDTH = 575;
var AJAX_CART_HEIGTH = 332;

var AjaxPopupClass = Class.create({
    loadQuickLookPopupButtons: function() {
        $$('.dg3xmultiItem').each(function(el) {
            el.onmouseover = function() {
                el.className = 'showPopupButton';
            };
            el.onmouseout = function() {
                el.className = 'dg3xmultiItem';
            };
        });
    },
    showQuickLookPopupWithProductTab: function(item_id, sectionid) {
	return this.showQuickLookPopup(item_id,'','info',sectionid)
    },
    showQuickLookPopupWithImagesTab: function(item_id, item_image_view_id, sectionid) {
	return this.showQuickLookPopup(item_id,item_image_view_id,'images',sectionid)
    },
    showQuickLookPopupWithSizechartTab: function(item_id, sectionid, sizechart_url) {
	myLightWindow.addOnCompleteAction(new Function('', 'loadSizechart("' + sizechart_url+ '")'));
	return this.showQuickLookPopup(item_id,'','sizechart',sectionid)
    },
    showQuickLookPopupWithVideosTab: function(item_id, sectionid) {
	return this.showQuickLookPopup(item_id,'','videos',sectionid)
    },
    showQuickLookPopup: function(item_id, item_image_view_id, type, section) {
        if (myLightWindow && !myLightWindow.clickFreshpairButton) {
	    var url = '/ajax_requests/item_quick_look_popup.php?item_id=' + item_id;
	    url += item_image_view_id ? '&image_view_id=' + item_image_view_id : '';
	    if (type) {
		url += '&view_type=' + type;
                Omniture.trackItemPageTabs(type);		
	    }
	    url += section ? '&sectionid=' + section : '';
	    var cookie = Cookie.getCookie('color_and_size');
	    if (cookie) {
		var color_and_size = cookie.split('|');
		url += color_and_size[0] ? '&color=' + color_and_size[0] : '';
		url += color_and_size[1] ? '&size=' + color_and_size[1] : '';
	    }
	    myLightWindow.activateWindow({
                href: url,
                height: QUICK_LOOK_HEIGHT,
                width: QUICK_LOOK_WIDTH,
                type: 'pageQuickLook',
                title: '',
                titleHeight: 25,
                itemid: item_id
            });
        }
        return true;
    },
    showSimplePopup: function(url, options) {
	var opt = new Hash({
	    width:QUICK_LOOK_WIDTH,
	    height:570,
	    title:'',
	    resize:true
        });
	opt = opt.merge(options);
	if (myLightWindow) {
	    myLightWindow.activateWindow({
	        href: url,
		height: opt.get('height'),
		width: opt.get('width'),
		type: 'simple',
		title: opt.get('title'),
		titleHeight: 30,
		autoresize: opt.get('resize')
	    });
	}
	return true;
    },			    
    ajaxViewAnotherColorAndSize: function(itemid, sectionid) {
	var url = '/ajax_requests/item_quick_look_popup.php?item_id=' + itemid + '&view_type=info&sectionid=' + sectionid;
        new Ajax.Request(url, {
            method: 'post',
            onSuccess: function(response) {
                AjaxPopup.displayQuickLookInsteadOfCartPopup(response,itemid);
            },
            onFailure: function(response) {
                AjaxPopup.onAjaxRequestFailure();
            }
        });
        return false;

    },

    changePopupParameters: function(titleHeight, titleClassName, titleHtml, response) {
	var titleBar = $('lightwindow_title_bar_title');
        titleBar.parentNode.className = titleClassName;
        titleBar.parentNode.style.height = titleHeight;
        titleBar.parentNode.parentNode.style.height = titleHeight;
        titleBar.innerHTML = titleHtml;
        var lwindow = $('lightwindow_contents');
        lwindow.innerHTML = response.responseText;
        lwindow.scrollTop = 0;
        return lwindow;
    },

    onCompleteCartPopupActions: function(lwindow) {
        printShoppingBagCount();
	new Effect.Highlight('itemInBag', {
            duration: 4.5
        });
    },
    
    resizeAjaxPopup: function(lwindow, content_height, content_width) {
	$('lightwindow_container').style.width = 'auto';
	$('lightwindow_container').style.height = 'auto';
	
	var browser_height = myLightWindow.dimensions.viewport.height - 70;
	var browser_width = myLightWindow.dimensions.viewport.width;
	var target_height = browser_height < content_height ? browser_height : content_height;
	var target_width = browser_width < content_width ? browser_width : content_width;
	
	var lightwindowContentsPercentWidthRezise = 100 * target_width / lwindow.getWidth();
	var lightwindowContentsPercentHeightRezise = 100 * target_height / lwindow.getHeight();	

	//0.27 is the percent difference between lightwindow_contets and lightwindow_container percent scaling
	if(content_width == QUICK_LOOK_WIDTH) {
	    var additionalResizePercentageValue = -0.27; //resize from ajax cart popup to quick look popup
	} else { 
	    var additionalResizePercentageValue = 0.27 ; //resize from quick look popup to ajax cart popup
	}
	 
	new Effect.Parallel([
	    new Effect.Scale(lwindow, lightwindowContentsPercentHeightRezise, {
		scaleX: false,
          	scaleContent: false
	    }),
	    
	    new Effect.Scale(lwindow, lightwindowContentsPercentWidthRezise, {
		scaleY: false,
		scaleContent: false
	    }),
	    new Effect.Scale('lightwindow_container', lightwindowContentsPercentWidthRezise + additionalResizePercentageValue, {
		scaleY: false,
		scaleContent: false,
		scaleFromCenter: true
	    })
	], {});
    },
    
    displayQuickLookInsteadOfCartPopup: function(response,itemid) {
        new Effect.Opacity('lightwindow_contents', {
            from: 1.0,
            to: 0,
            duration: 0.5,
            afterFinish: function() {
                var lwindow = AjaxPopup.changePopupParameters('25px', '', '', response);
		AjaxPopup.prepareItemPopupContent();
		AjaxPopup.getLiveInventory(itemid);
		AjaxPopup.resizeAjaxPopup(lwindow, QUICK_LOOK_HEIGHT, QUICK_LOOK_WIDTH);
		new Effect.Opacity('lightwindow_contents', {
                    from: 0,
                    to: 1.0,
                    duration: 0.5,
		    delay: 0.5,
                    afterFinish: function() {
                    }
                });
            }
        });
        return false;
    },
    
    displayCartPopupInsteadOfQuickLookPopup: function(response) {
	new Effect.Opacity('lightwindow_contents', {
            from: 1.0,
            to: 0,
            duration: 0.5,
	    afterFinish: function() {
                var lwindow = AjaxPopup.changePopupParameters('40px', 'ajaxCartTitleBar', '', response);
		//we need to use #itemInBag height + additional space below calculated manually (instead of just #ajaxCartPopup height)
                AjaxPopup.resizeAjaxPopup(lwindow,$('itemInBag').getHeight() + 190, AJAX_CART_WIDTH);
		new Effect.Opacity('lightwindow_contents', {
                    from: 0,
                    to: 1.0,
                    duration: 0.5,
		    delay: 0.5,
                    afterFinish: function() {
                        AjaxPopup.onCompleteCartPopupActions(lwindow);
                    }
                });
            }
        });
        return false;
    },

    ajaxAddToCartOnQuickLookPopup: function(form) {
	var selected_qties;
        if (selected_qties = checkItems(form)) {
            var cartUrl = '/ajax_requests/add_to_cart.php?' + this.serializeQtiesAndTrackAddToBag(selected_qties);
            new Ajax.Request(cartUrl, {
                method: 'get',
                onSuccess: function(response) {
                    AjaxPopup.displayCartPopupInsteadOfQuickLookPopup(response);
                },
                onFailure: function(response) {
                    AjaxPopup.onAjaxRequestFailure();
                }
            });
        }
        return false;
    },

    ajaxAddToCartOnItemPage: function(form, displayPopup) {
	var selected_qties;
        if (selected_qties = checkItems(form)) {
            if (displayPopup && myLightWindow && !myLightWindow.clickFreshpairButton) {
		myLightWindow.addOnCompleteAction(new Function('', "updateItemFormWithSize("+form.itemid.value+", $('size_id').value, '', 1);"));
                this.showAjaxCartPopup(this.serializeQtiesAndTrackAddToBag(selected_qties));
		return false;
            }
            return true;
        }
        return false;
    },

    showAjaxCartPopup: function(form_serialized) {
	myLightWindow.activateWindow({
            href: '/ajax_requests/add_to_cart.php?' + form_serialized,
            height: AJAX_CART_HEIGTH,
            width: AJAX_CART_WIDTH,
            type: 'pageAjaxCart',
            title: '',
            titleHeight: 40
        });
	
        return true;
    },

    getLiveInventory: function(item_id) {
        new Ajax.Request('/ajax_requests/item_live_inventory.php?itemid=' + item_id, {
            onFailure: function(transport) {
                AjaxPopup.onAjaxRequestFailure();
            },
            evalJS: true
        });
    },
    onAjaxRequestFailure: function() {},
    prepareItemPopupContent: function (){
	$$('#ajax-form select').each(function(el) {
            el.style.display = 'inline';
        });
	var firstImageThumbnail = $$('#carousel-wrapper-images img')[0];
	if(firstImageThumbnail) {
	    firstImageThumbnail.onclick();
	}
	var firstVideoThumbnail = $$('#carousel-wrapper-videos img')[0];
	if(firstVideoThumbnail) {
	    firstVideoThumbnail.onclick();
	}
	var loadSizechart = $('load-sizechart');
	if(loadSizechart){
	    loadSizechart.onclick();
	}
    },
    serializeQtiesAndTrackAddToBag: function(selected_qties) {
	var serialized_qties = "";
	selected_qties.each( function (qty) { 
				   	serialized_qties += 'barcodes[' + qty.get("barcode_id") + ']=' + qty.get("qty") + '&';
					Omniture.trackAddToBag(qty.get("barcode"), 'Item Page');
                		    });
	return serialized_qties;
    },
    updatePopupContainer: function(popup_type) {
	var url = '/cart_popups.php';
	var params = {type:popup_type, only_content:true};
	new Ajax.Updater('right_popup_container', url, {
	    method:'get',
            parameters: params
	});
	return true;
    },
    showSkidPopup: function(popupContentFile) {
	 myLightWindow.activateWindow({
            href: '/ajax_requests/' + popupContentFile,
            width: 800,
	    height: 850,
            type: 'simple',
            title: '',
	    titleHeight:0
        });
        return false;
    },
    showInlinePopup: function(id, width, height, title, titleHeight) {
	if ( typeof(title) != 'string') {
	   title = '';
	}
	if ( typeof(titleHeight) != 'number' || titleHeight < 0) {
	   titleHeight = 0;
        }
	if ( typeof(height) != 'number' || height < 0) {
	   titleHeight = 0;
        }
	if ( typeof(width) != 'number' || width < 0) {
	   titleHeight = 0;
        }
	myLightWindow.activateWindow({type: "inline",	
	                              height: height,
				      width: width,
				      titleHeight: titleHeight,
				      title: title,
				      href: id});			
    },
    
    showFlowPlayer: function(player_id) {
	if(!player_id) player_id = 'player';
        flowplayer(player_id, "/fp_content/swf/flowplayer/flowplayer.commercial-3.1.1.swf", {
            key: $(player_id).getAttribute('key'),
            clip: {
                autoPlay: true,
                autoBuffering: false
            }
        });
    }			
});

var AjaxPopup = new AjaxPopupClass();
