var QUICK_LOOK_WIDTH = 721;
var QUICK_LOOK_HEIGHT = 550;
var AJAX_CART_WIDTH = 560;
var AJAX_CART_HEIGTH = 502;
var TRACKING_PIXEL_TELL_APART_ACCOUNT_NUMBER = "5qZ7bZN0EjR2";

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)
    },
    showQuickLookPopupWithReviewsTab: function(item_id, sectionid) {
	myLightWindow.addOnCompleteAction(new Function('', 'loadReviews('+ item_id +')'));
	myLightWindow.addOnCompleteAction(new Function('', 'snippet(document)'));
	return this.showQuickLookPopup(item_id,'','reviews',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;
    },

    showBehindTheBrandVideoPopup: function(popupContentFile, mkVideo){
	myLightWindow.activateWindow({
            href: '/ajax_requests/' + popupContentFile,
            height: 600,
            width: mkVideo ? 620 : 750,
            type: 'page',
            title: '',
            titleHeight: 40
        });
	myLightWindow.addOnCompleteAction(initializeFlowPlayerForBehindTheBrandPopup);

	return false;
    },

    showNud2009WinnerVideoPupup: function(popupContentFile,id){
	myLightWindow.activateWindow({
            href: '/ajax_requests/' + popupContentFile + '?id=' + id,
            height: 500,
            width: 600,
            type: 'page',
            title: '',
            titleHeight:0
        });

	myLightWindow.addOnCompleteAction(showFlowPlayer);
	return false;
    },

    showFlowPlayer: function(player_id) {
        flowplayer(player_id, "/fp_content/swf/flowplayer/flowplayer.commercial-3.1.1.swf", {
            key: $(player_id).getAttribute('key'),
            clip: {
                autoPlay: false,
                autoBuffering: false
            }
        });
    },

    toggleNud2009Video: function(activeImgEl, videoTitle, videoDesc, videoFilePath, playerId) {
	var player = $(playerId);
	$('btb-video-title').innerHTML = videoTitle;
	player.setAttribute('href',videoFilePath); 
	flowplayer(playerId, "/fp_content/swf/flowplayer/flowplayer.commercial-3.1.1.swf", {
	    key: player.getAttribute('key'),
	            clip: {
                        autoPlay: false,
			autoBuffering: false
		     }
	});
	$('btb-video-desc').innerHTML = videoDesc;
	$$('#carousel-wrapper-images img').each(function(el) {
	    el.parentNode.className = '';
	});
	activeImgEl.parentNode.className = 'active';
    },

    changeDieselImage: function(activeImgEl, imageTitle, imageFilePath, imageWidth, imageHeigh) {
	$('btb-photo-name').innerHTML = imageTitle;
	var image = $('diesel-image');
	image.height = imageHeigh;
	image.width = imageWidth;
	image.src = imageFilePath;

	$$('#carousel-wrapper-images img').each(function(el) {
	    el.parentNode.className = '';
	});
	activeImgEl.parentNode.className = 'active';
       
   },

    changeDieselImageOffset: function(child,widthImg,heightImg) {
	child = $(child);
	var width = widthImg;
	var height = heightImg;
	var offsetTop = (480 - height) /2;
	var offsetLeft = (310 - width)/2;
	child.setStyle('margin-top:' + offsetTop + 'px;');
	child.setStyle('margin-left:' + offsetLeft + 'px;');
    },

    toggleBehindTheBrandVideo: function(activeImgEl, videoTitle, videoDesc, videoFilePath) {
	var player = $("player");
	$('btb-video-title').innerHTML = videoTitle;
	player.setAttribute('href',videoFilePath); 
	$('carousel').show();
	$('btb-end-splash').hide();
	playFlowPlayer(videoTitle, 'Behind The Brand Video');
	$('btb-video-desc').innerHTML = videoDesc;

	$$('#carousel-wrapper-images img').each(function(el) {
	    el.parentNode.className = '';
	});
	activeImgEl.parentNode.className = 'active';
    },				  

    showSimplePopup: function(url, options) {
	var opt = new Hash({
	    width:QUICK_LOOK_WIDTH,
	    height:570,
	    title:'',
	    resize:true,
	    resize_x:true,
	    resize_y:true,
	    titleHeight:30
	});
	opt = opt.merge(options);
	if (myLightWindow && !myLightWindow.clickFreshpairButton) {
	    myLightWindow.activateWindow({	
	        href: url,
		height: opt.get('height'),
		width: opt.get('width'),
		type: 'simple',
		title: opt.get('title'),
		titleHeight: opt.get('titleHeight'),
		autoresize: opt.get('resize'),
		resize_x: opt.get('resize_x'),
		resize_y: opt.get('resize_y')
	    });
	    
	}

	return true;
    },

    showSimplePopupOnFreshpairPage: function(url,options){
	myLightWindow.addOnCompleteAction(AjaxPopup.hidePlayer);
	myLightWindow.addOnDeactivateWindowAction(AjaxPopup.showPlayer);
	this.showSimplePopup(url,options);
    },

    showSimplePopupWithRecaptcha: function(url,options){
	myLightWindow.addOnCompleteAction(function(){creteReacapthaImage('');});
	myLightWindow.addOnCompleteAction(AjaxPopup.hidePlayer);
	myLightWindow.addOnDeactivateWindowAction(AjaxPopup.showPlayer);
	this.showSimplePopup(url,options);
    },

    showPlayer: function(){
	if($('player') != null){
	    $('player').show();
	    $('player').setStyle('display:block;height:325px;width:400px;');
	}
    },

    hidePlayer: function(){
	if($('player') != null){
	    $('player').hide();
	}
    },

    sendEmailToFriend: function(form,target){
     var url = '/ajax_requests/send_nud_2009_email_friend.php?' + Form.serializeElements($(form.id).getElements()); 
  
	new Ajax.Updater(target, url, {
        	asynchronous: true,
        	evalScripts: true,
	        method: 'post',
	        onComplete: function(transport) {
                    if(200 == transport.status){
			creteReacapthaImage('');
		    }
	        }
    	});
    },

    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;
    },

    resizeSimpleAjaxPopup: function(lwindow, content_height, content_width, resize_x, resize_y) {
	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();	

	var effects = [];
	// Y vertical
	if(resize_y) {
	    effects.push(new Effect.Scale(lwindow, lightwindowContentsPercentHeightRezise, {
		scaleX: false, scaleContent: false }));
	    effects.push(new Effect.Scale('lightwindow_container', lightwindowContentsPercentHeightRezise, {
		scaleX: false, scaleContent: false, scaleFromCenter: true }));
	}
	// X horizontal
	if(resize_x) {
	    effects.push(new Effect.Scale(lwindow, lightwindowContentsPercentWidthRezise, {
		scaleY: false, scaleContent: false }));
	    effects.push(new Effect.Scale('lightwindow_container', lightwindowContentsPercentWidthRezise, {
		scaleY: false, scaleContent: false, scaleFromCenter: true }));
	}
	
	new Effect.Parallel(effects, {});
    },

    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.setStyles(false);
		
		new Effect.Opacity('lightwindow_contents', {
                    from: 0,
                    to: 1.0,
                    duration: 0.5,
			      delay: 0.5,
			      afterFinish: function(){
				  AjaxPopup.resizeAjaxPopup(lwindow, QUICK_LOOK_HEIGHT, QUICK_LOOK_WIDTH);
			      }
                });
            }
        });
        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);
		//$('lightwindow_contents').style.overflow = 'hidden';
		
		var height = 0;
		var higherLinksBox = 0;
		$('shoppingBag').childElements().each(function (e){
		    height += e.getHeight();
		})
		$('relatedLinksBox').childElements().each(function (el){
		    if (higherLinksBox < el.getHeight()) {
			higherLinksBox = el.getHeight();
		    }
		})
				
		new Effect.Opacity('lightwindow_contents', {
                    from: 0,
                    to: 1.0,
                    duration: 0.5,
		    delay: 0.5,
                    afterFinish: function() {
                        AjaxPopup.resizeAjaxPopup(lwindow, AjaxPopup.getAjaxCartCrossBrowserHeight(), AJAX_CART_WIDTH);
			AjaxPopup.onCompleteCartPopupActions(lwindow);
		    }
                });
            }
        });
        return false;
    },
    
    onCompleteCartPopupActions: function(lwindow) {
        printShoppingBagCount();
	AjaxPopup.setAjaxCartStyles();
	new Effect.Highlight('itemInBag', {
            duration: 4.5
        });
    },
    
    setAjaxCartStyles: function() {
	if ($('ajaxCartPopup')) {
	    this.setStyles(true);
	}
    },
    
    setStyles: function(set_styles) {
	$$('.rounded-corners .bottom3')[0].setStyle({
	    backgroundColor: set_styles ? '#F1F1F1' : '#FFF'
	});
	//$('lightwindow_contents').style.overflowY = 'hidden';
    },
    
    ajaxAddToCartOnQuickLookPopup: function(form,displayTrackingPixelTellApart) {
	var selected_qties;
        if (selected_qties = checkItems(form)) {
            var cartUrl = '/ajax_requests/add_to_cart.php?' + this.serializeQtiesAndTrackAddToBag(selected_qties,displayTrackingPixelTellApart);
            new Ajax.Request(cartUrl, {
                method: 'get',
                onSuccess: function(response) {
                    AjaxPopup.displayCartPopupInsteadOfQuickLookPopup(response);
                },
                onFailure: function(response) {
                    AjaxPopup.onAjaxRequestFailure();
                }
            });
        }
        return false;
    },

    ajaxAddToCartOnItemPage: function(form, displayPopup,displayTrackingPixelTellApart) {
	var selected_qties;
        if (selected_qties = checkItems(form)) {
            if (displayPopup && myLightWindow && !myLightWindow.clickFreshpairButton) {
		myLightWindow.addOnCompleteAction(new Function('', "clearColorSelect();"));
		myLightWindow.addOnCompleteAction(new Function('', "myLightWindow._toggleTroubleElements('hidden', false);"));
                this.showAjaxCartPopup(this.serializeQtiesAndTrackAddToBag(selected_qties,displayTrackingPixelTellApart));
		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();
	}
	var loadReviews = $('load-reviews');
	if(loadReviews){
	    loadReviews.onclick();
	}
    },
    serializeQtiesAndTrackAddToBag: function(selected_qties,displayTrackingPixelTellApart) {
	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');
                		    });
	if(displayTrackingPixelTellApart) {
	    this.addToShoppingCart(selected_qties);
	}
	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;
    }, 
    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});			
    },
    getAjaxCartCrossBrowserHeight: function() {
	/* #relatedLinksBox - it has normal height on any browser
	   #itemInBag - it doesn't has normal height under IE6, that's why we sum:
             1) #itemInBag - (items <table> dinamic height) (static value!)
             2) static height of #itemSummary: 103px 
             3) static height of #ajaxCheckoutNav: 64px
              it gives us final #shoppingBag height: (items <table> dinamic height) + 226px   
        */
	return $('relatedLinksBox').getHeight() + $$('#itemInBag table')[0].getHeight() + 226;
    },

    addToShoppingCart: function(selected_qties) {
	if(__cmbLoaded) {
	    var action = TellApartCrumb.makeCrumbAction("'" + TRACKING_PIXEL_TELL_APART_ACCOUNT_NUMBER + "'","updatecart");
	    selected_qties.each( function (qty) {
		action.beginItem();
		action.setItemAttr("SKU",qty.get("sku"));
		action.setItemAttr("ProductPrice",qty.get("item_price"));
		action.setItemAttr("ProductCurrency","USD");
		action.setItemAttr("ItemCount",qty.get("qty"));
		action.endItem();

	    });
	    action.finalize();
	}
    }
    
});

var AjaxPopup = new AjaxPopupClass();
