﻿/*
 Author:  avc
 Date:    08/12/2009
 Input:   see defaults.
 Ouput:   n/a
 Example: budk product.aspx
 About:
  This is a jquery plugin that will add a quickview button to any matched
  element.
*/
var QV_pid = 0;
var sizeArrayString = "";
var QVRestrictedStates = "";
// create closure
(function($) {  
  $.fn.quickview = function(options) {  
    	
	var main_opts = $.extend({}, $.fn.quickview.defaults, options);
	

	return this.each(function() {
	  //$(this) = $(this);

	  var opts = $.meta ? $.extend({}, main_opts, $(this).data()) : main_opts;
      
        $(this).bind('mouseover', function(e){
            var pos = $(this).offset();//$(this).position();
            var style = 'z-index:9999;cursor:pointer;position:absolute;top:'+(pos.top+100)+'px;left:'+(pos.left+30)+'px;';
            
            $('.qvbutton').remove();
            
            $('body').append('<img pid="' + $(this).attr("pid") + '" class="qvbutton" src="' + opts.AppTheme + '/graphics/quicklook_btn.gif" style="'+style+'" />')            
            
            $('.qvbutton').bind('click', function(e){
                var t=0;
                var pid = $(this).attr("pid");
                QV_pid = pid;
                HideCartHover();
                QVRestrictedStates = "";
                
                if ($("#QuickView").css("display") != "none") 
                {
                    $("#QuickView").fadeOut("slow");
                    t=500;
                }   
                
                setTimeout(function(){
                    $.ajax({
                        url: '/WebServices/Product.asmx/QuickView',
                        data: 'pk_pid='+pid,
                        type: 'GET',
                        dataType: 'xml',
                        timeout: 30000,
                        error: function(){
                            //debug('Error loading document types');
                        },
                                                                        
                        success: function(xml){                                                        
                            $(xml).find('results').find('product').each(function(){
                                
                                var id = $(this).attr('id');
                                var sid = $("sid", this).text();
                                var sku = $("sku", this).text();
                                var pName = $("name", this).text();
                                var image = $("imageName", this).text();
                                var sDesc = $("shortDescription", this).text();
                                var lDesc = $("longDescription", this).text();
                                var url = $("seo_url", this).text();
                                var hasZoom = $("hasZoomImage", this).text();
                                var brand = $("brand", this).text();
                                var msrp = parseFloat($("SuggestedRetail", this).text()).toFixed(2);
                                var regPrice = parseFloat($("regularPrice", this).text()).toFixed(2);
                                var salePrice = parseFloat($("salePrice", this).text()).toFixed(2);
                                var memberPrice = parseFloat($("memberPrice", this).text()).toFixed(2);
                                var specialPrice = parseFloat($("specialPrice", this).text()).toFixed(2);
                                var discountPrice = parseFloat($("discountPrice", this).text()).toFixed(2);
                                var ratingCount = $("ratingCount", this).text();
                                var ratingImage = $("ratingImage", this).text();
                                var qtyonhand = $("qtyonhand", this).text(); 
                                var addtlShipping = $("AdditionalShipping", this).text();                                                                       
                                var boadate = $("BOADate", this).text();
                                var restrictedshipping = $("attributeValue1", this).text();                                                                       
                                var trimlDesc = "";
                                var discontinued = $("Discontinued", this).text();    
                                var priceTitle = $("priceTitle", this).text();                                                                      
                                var restrictedStates = $("restrictedStates", this).text();
                                
                                //01-25-10 13:10:18 avc >> reset some fields
                                $('.regPrice','#QuickViewText').html('');
                                $('.salePrice','#QuickViewText').html('');
                                $('.memberPrice','#QuickViewText').html('');
                                $('.specialPrice','#QuickViewText').html('');                                
                                
                                QVRestrictedStates = restrictedStates;
                                
                                //10-28-09 09:55:41 avc >> use sku if now seourl is available
                                if(url == null || url == '') {
                                    url = 'product.aspx?sku=' + sku;
                                }
                                
                                //alert(restrictedshipping);
                                $("div.ltWLmsg").empty();
                                
                                if (hasZoom == "True")
                                {                                          
                                    $("#QVZoomLink").attr("href", "javascript: void window.open('/zoomimages.aspx?pid="
                                      +id+"','zoomimgwindow','location=0,status=0,scrollbars=0,width=600,height=600'); ");
                                }                                            
                                
                                QVLongDescription = lDesc;
                                $("#morelink").show();                                                                
                                
                                if (lDesc.length > 200)
                                {                                    
                                    trimlDesc = lDesc.substring(0,200);
                                } 
                                else
                                {                                 
                                    trimlDesc = lDesc;                                                                        
                                    $("#morelink").hide();
                                }
                                if (sDesc.length == 0)
                                {                                    
                                    $(".pDesc","#QuickViewText").html(trimlDesc);
                                }
                                else
                                {                                             
                                    $(".pDesc","#QuickViewText").html(sDesc);                                                                                                                                                     
                                }                                                                   
                                
                                $("#QVImageLink").attr("href", "/" + url);
                                $("img", "#QuickViewImage").attr("src", "/productimages/250/" + image).css({width:'250px', height:'250px'});                                    
                                $("a:first","#QuickViewText").attr("href", "/" + url).text(pName);
                                $(".brandName","#QuickViewText").text(brand);
                                $(".qvReviews","#QuickViewText").text("(" + ratingCount + " Reviews)");
                                $("img",".qvRating").attr("src", opts.AppTheme + "/graphics/stars/" + ratingImage).css({width:'61px', height:'12px'});
                                $(".sku","#QuickViewText").text(sku);
                                
                                //$(".msrp").text("MSRP: $" + msrp).toFixed(2);
                                if(msrp > regPrice) {
                                    $(".msrp","#QuickViewText").text("MSRP: $" + msrp).show();                                
                                } else {
                                    $(".msrp","#QuickViewText").text('').hide();                                
                                }
                                $(".regPrice","#QuickViewText").text(priceTitle + " $" + regPrice).css("text-decoration", "none");
                                    
                                if (msrp <= 0)
                                {
                                    $(".msrp").hide();
                                }
                                
                                //alert('spec: '+specialPrice+'\r\n mem: '+memberPrice+'\r\n sale: '+salePrice+'\r\n disc: '+discountPrice);
                                
                                if(parseFloat(specialPrice) > 0)
                                {
                                    if(parseFloat(memberPrice) > 0) 
                                    {
                                        if (parseFloat(salePrice) > 0 && parseFloat(salePrice) < parseFloat(regPrice)) 
                                        {
                                            $(".regPrice","#QuickViewText").css("text-decoration", "line-through");
                                            $(".salePrice","#QuickViewText").text("Sale Price: $" + salePrice).css("text-decoration", "line-through");
                                            $(".memberPrice","#QuickViewText").text("Buyers Club: $" + memberPrice).css("text-decoration", "line-through");
                                            $(".specialPrice","#QuickViewText").text("Now: $" + specialPrice);
                                        }
                                        else
                                        {
                                            $(".regPrice","#QuickViewText").text(priceTitle + " $" + regPrice).css("text-decoration", "line-through");
                                            $(".memberPrice","#QuickViewText").text("Buyers Club: $" + memberPrice).css("text-decoration", "line-through");
                                            $(".specialPrice","#QuickViewText").text("Now: $" + specialPrice);
                                            $(".salePrice","#QuickViewText").hide();
                                        }
                                    }
                                    else if (parseFloat(salePrice) > 0)
                                    {
                                        $(".regPrice","#QuickViewText").css("text-decoration", "line-through");
                                        $(".salePrice","#QuickViewText").text("Sale Price: $" + salePrice).css("text-decoration", "line-through");
                                        $(".specialPrice","#QuickViewText").text("Now: $" + specialPrice);
                                        $(".salePrice","#QuickViewText").show();
                                    }
                                    else
                                    {
                                        $(".regPrice","#QuickViewText").text(priceTitle + " $" + regPrice).css("text-decoration", "line-through"); 
                                        $(".specialPrice","#QuickViewText").text("Now: $" + specialPrice);
                                        $(".salePrice","#QuickViewText").hide();
                                    }
                                }
                                else 
                                {
                                    $(".specialPrice","#QuickViewText").hide();
                                    if(parseFloat(memberPrice) > 0) 
                                    {
                                        if (parseFloat(salePrice) > 0 && parseFloat(salePrice) < parseFloat(regPrice)) 
                                        {
                                            $(".regPrice","#QuickViewText").css("text-decoration", "line-through");
                                            $(".salePrice","#QuickViewText").text("Sale Price: $" + salePrice).css("text-decoration", "line-through");
                                            $(".memberPrice","#QuickViewText").text("Buyers Club: $" + memberPrice);
                                        }
                                        else
                                        {
                                            $(".regPrice","#QuickViewText").text(priceTitle + " $" + regPrice).css("text-decoration", "line-through");
                                            $(".memberPrice","#QuickViewText").text("Buyers Club: $" + memberPrice);
                                            $(".salePrice","#QuickViewText").hide();
                                        }
                                        
                                        if(discountPrice > 0) {
                                            $(".memberPrice","#QuickViewText").text("Buyers Club: $" + discountPrice);
                                        }                                                                                    
                                    }
                                    else if (parseFloat(salePrice) > 0 && parseFloat(salePrice) < parseFloat(regPrice))
                                    {
                                        $(".regPrice","#QuickViewText").css("text-decoration", "line-through");
                                        $(".salePrice","#QuickViewText").text("Sale Price: $" + salePrice).show();
                                        
                                        //01-25-10 12:37:34 avc >>
                                        if(discountPrice > 0 && parseFloat(discountPrice) < parseFloat(regPrice)) {
                                            $(".salePrice","#QuickViewText").text("Sale Price: $" + discountPrice).show();
                                        }
                                    }
                                    else
                                    {
                                        $(".regPrice","#QuickViewText").text(priceTitle + " $" + regPrice);   
                                        //$(".salePrice","#QuickViewText").hide();
                                        //01-25-10 12:37:24 avc >>
                                        if(discountPrice > 0 && parseFloat(discountPrice) < parseFloat(regPrice)) {
                                            $(".regPrice","#QuickViewText").css("text-decoration", "line-through");
                                            $(".salePrice","#QuickViewText").text("Sale Price: $" + discountPrice).show();
                                        }                                        
                                    }
                                }
                                
                                if (qtyonhand <= 0 && boadate == null)
                                {
                                    $(".ltStockMessage","#QuickViewText").text("[On Backorder]"); 
                                }
                                else if (qtyonhand <= 0 && boadate != null)
                                {
                                    $(".ltStockMessage","#QuickViewText").text("[On Backorder]");
                                    $("#ltStockMessageSize").text("Est. ship date " + dateFormat(boadate, 'mm/dd/yyyy')).show();
                                }                                    
                                else                            
                                {
                                    $(".ltStockMessage","#QuickViewText").text("[In Stock]");                                                                        
                                    $("#ltStockMessageSize").hide();
                                }
                                
                                if (addtlShipping > 0)
                                {
                                    $(".ltOverSizeMessage","#QuickViewText").text("[Over Size]");
                                }
                                
                                if (restrictedStates != "")
                                {
                                    $(".ltRestrictedShippingMessage","#QuickViewText").text("[Restricted Shipping to " + restrictedStates + ".]").show();
                                }
                                else
                                {
                                    $(".ltRestrictedShippingMessage","#QuickViewText").hide();                                    
                                }
                                
                                $(".cartbtn","#QuickViewText").unbind("click").bind("click", function(){ AjaxToCart(pid) }); 
                                $(".wishlistbtn","#QuickViewText").unbind("click").bind("click", function(){ AddToWishlist(pid) });
                                $(".viewfulldetailsbtn","#QuickViewText").unbind("click").bind("click", function(){ window.location= "/" + url});                                    
                                $(".cartbtn").show();
                                $(".wishlistbtn").show();                                                                                                                                                                    
                                $(".WLmsg").hide();
                                
                                //if on MAT or Wholesale do not show wishlist
                                if (sid == 2 || sid == 3)
                                {
                                    $(".wishlistbtn").hide();                                                                                                                                                                                                  
                                }    
                                if (sid == 2 || sid == 3 || sid == 4)                           
                                {
                                    $(".qvRating").hide();
                                }
                                
                                 if (qtyonhand<= 0 && discontinued != 0)
                                {
                                    $(".ltStockMessage","#QuickViewText").text("[Discontinued no longer Available]");
                                    $(".wishlistbtn").hide();
                                    $(".cartbtn").hide();                                    
                                }
         
                                $("#QuickView").bind('dragstart',function( event ){
                                    if ( !$(event.target).is('.handle') ) return false;
                                    $( this ).addClass('active');
                                }).bind('drag',function( event ){
                                    $( this ).css({
                                        top: event.offsetY,
                                        left: event.offsetX
                                    });
                                }).bind('dragend',function( event ){
                                    $( this ).removeClass('active');
                                });
                                
                                //QuickView popup positioning
                                //10-12-09 15:04:46 avc >>
                                //$("#QuickView").css({top:getQuickLookY(), left:(screen.availWidth/2-240)});                                    
                                $("#QuickView").center().fadeIn("slow");
                                try {
                                    document.getElementById('ProductTabs').tabber.tabShow(0);
                                }
                                catch(err){}
                            });
                                                        
                            $('#divAltImages').empty();                            
                            
                            $(xml).find('results').find('alternateimages').find('image').each(function(){
                                var image = $(this).attr('image');                            
                                var tag2 = '<img path="'+image+'" onmouseover="qvShowAltImage(this);" src="'+ProductImagePath+'50/' + image + '" width="50" height="50"></image>';                                
                                $('#divAltImages').append(tag2);
                            });
                            
                            $('#divMarketingIcons').empty();                            
                            
                            $(xml).find('results').find('marketingIcons').find('icon').each(function(){
                                var icon = $(this).attr('icon');                            
                                var tag = '<img src="' + opts.AppTheme + '/MarketingIcons/' + icon + '" width="50" height="50"></image>';                                
                                $('#divMarketingIcons').append(tag);                                
                            });
                            
                            //this is for products with size options
                            $('#QuickViewSizeDD').empty();                            
                            var first = 0;
                            var sizelist = '';
                            var itemAdditionalPriceMessage = "";
                            var cnt =0;
                            $(xml).find('results').find('productsizes').find('size').each(function(){
                            cnt++;
                                if (first == 0)
                                {
                                    //$('#QuickViewSizeDD').append("<select name='ddlQVsize'>");
                                    sizelist = "<select onchange='UpdateQVStockMessage_OnChange(this);' name='ddlQVsize'>";
                                    first = 1;                                
                                }
                                
                                size = $(this).attr('size');                                
                                sizeArrayString += size + '|';
                                var sizeResult = size.split("~");
                                var pid = sizeResult[0];
                                var sku = sizeResult[1];
                                var bestprice = sizeResult[2];
                                var parentbestprice = sizeResult[3];
                                var backorderarrivaldate = sizeResult[4];
                                var Qtyonhand = sizeResult[5];
                                if (bestprice > parentbestprice)
                                {   //if this child item is more expensive than the parent, make sure to note that in the dropdown.
                                    itemAdditionalPriceMessage = " - Add " + formatCurrency(bestprice - parentbestprice);
                                }
                                else
                                {
                                    itemAdditionalPriceMessage = "";
                                }
                                if (cnt == 1)
                                {
                                    if (Qtyonhand < 1 && backorderarrivaldate != '')
                                    {                                        
                                        $("#ltStockMessageSize").text("Est. ship date " + dateFormat(backorderarrivaldate, 'mm/dd/yyyy')).show();
                                    }
                                    else 
                                    {
                                        $("#ltStockMessageSize").text("").hide();
                                    }
                                }   
                                sizelist += "<option value='" + pid + "'>" + (sku.substring(sku.lastIndexOf(' '))) + itemAdditionalPriceMessage + "</option>";                                

                            });
                            sizeArrayString = sizeArrayString.substring(0,sizeArrayString.length -2)
                            if (first != 0)
                            {
                                 $('#QuickViewSizeDD').append(sizelist);
                            }
                        }
                    });
                }, t);                    
            });//end click            
        });//end mouseover
        
        $(this).bind('mouseout', function(e){
            var pos = $(this).offset();//$(this).position();
            var mintop = pos.top;
            var minleft = pos.left;                
            var maxtop = pos.top + 140;
            var maxleft = pos.left + 140;
            var mousex = e.pageX;
            var mousey = e.pageY;
          
            
            if(mousey <= mintop || mousex <= minleft || mousex >= maxleft || mousey >= maxtop) {
                $('.qvbutton').remove();
            }
        });//end mouseout         
	});//end each
  };//end quickview

  //use: $.fn.hilight.defaults.foreground = 'blue';  
  $.fn.quickview.defaults = {
    defaultTextClass: 'defaultText',
    AppTheme: 'App_Themes/budk.com'
  };
// end of closure
})(jQuery);

//08-12-09 avc >>globals
var QVLongDescription = "";

function CloseQuickView()
{
    $("#QuickView").fadeOut("slow");
    return false;
} 

//10-12-09 15:04:08 avc >>
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

//10-12-09 15:09:58 avc >> dont use this anymore, use the center (jQuery.fn.center ex. obj.center) function
//added to jquery ex. [$('.something').center();]
function getQuickLookY() 
{
    $("#txtQVQuantity").val(1);
    //$("#ProductTabs").show(1);
    var windowHeight = 0;
    var windowBottom = 0;
    var windowTop = 0;

    if (typeof(window.innerHeight) == 'number') {
	    windowHeight = window.innerHeight;
	    //alert(windowHeight);
    }
    else {
        windowHeight = document.body.offsetHeight;
    }	
    if (typeof(window.pageYOffset) == 'number') {
	    windowBottom = windowHeight + window.pageYOffset;
    }
    else {
	    if (document.body && document.body.scrollTop) {
		    windowBottom = windowHeight + document.body.scrollTop;
	    }
	    else {
		    if (document.documentElement && document.documentElement.scrollTop) {
			    windowBottom = windowHeight + document.documentElement.scrollTop;
		    }
	    }
    }
	
    windowTop = (windowBottom - windowHeight);

    if (windowTop < 0) {
	    windowTop = 0;
    }

    var y = Math.round(windowTop);
    y = (y + 150);
    return y;	
}

function ShowLongDescription()
{    
    $(".pDesc","#QuickViewText").html(QVLongDescription);
    $("#morelink").hide();
}

function AjaxToCart(pid) {
    //var qty = document.getElementById("txtQVQuantity").value;
    var qty = $("#txtQVQuantity").val();
    var ddsize = $("#QuickViewSizeDD option:selected").val();      
    if (ddsize != null && ddsize != "") {
        pid = ddsize;
    }

    if(QVRestrictedStates.indexOf(QVShippingState) != -1 && QVRestrictedStates != '' && QVShippingState != '') {
        if($('#rstshippingmessagepanel').length > 0) {
            //formatted alert
            $('.rsmInfoContainer','#rstshippingmessagepanel').html('<p>This item has not been added to your cart.</p>');
            qvShowModal('#rstshippingmessagepanel', 'Restricted Shipping Notification');
        } else {
            //standard alert
            alert('Restricted Shipping Notification\r\nUnfortunatly your ship to state is restricted by law.\r\nThis item has not been added to your cart.');
        }
        CloseQuickView();
    } else {
        $.ajax({
            url: '/WebServices/Cart.asmx/AddToCartQty',
             data: 'PK_PID='+pid+'&qty='+qty,       
            type: 'POST',
            dataType: 'xml',
            timeout: 30000,
            error: function(){
                alert('error adding to cart');
                //debug('Error loading document types');
            },
            success: function(xml){  
                if ($(xml).find('boolean').text() == "true")
                {
                    CloseQuickView();

                    //document.location = "/cart.aspx";
                    $.scrollTo({ top: 0, left: 0 }, 800);

                    CartItemCount++;
                    
                    //$("#CartTopBox").trigger("mouseover");                
                    BindCartHover();
                    
                    if(String(document.location).indexOf('cart.aspx') != -1) {
                        document.location = '/cart.aspx';
                    }
                }
            }
        }); 
    }   
}

function AddToWishlist(pid) {
    //var qty = document.getElementById("txtQVQuantity").value;
    var qty = $("#txtQVQuantity").val();
    var wishlistmsg = "This item has been added to your "
    
    if(IsUserAuthenticated == 'True') {
        $.ajax({
            url: '/WebServices/Cart.asmx/AddToWishlist',
            data: 'PK_PID='+pid+'&qty='+qty,             
            type: 'POST',
            dataType: 'xml',
            timeout: 30000,
            error: function(){
                alert('error');
                //debug('Error loading document types');
            },
            success: function(xml){  
                if (qty > 1)
                {
                    wishlistmsg = "The items have been added to your "
                }
                if ($(xml).find('boolean').text() == "true")
                {
                    $(".wishlistbtn").hide();                
                    $(".ltWLmsg","#QuickViewText").html(wishlistmsg + "<a href='/mywishlist.aspx'>wish list</a>.");                                
                    //CloseQuickView();
                    //document.location = "/WishList.aspx";
                }
            }
        });  
    } else {
        document.location = '/login.aspx?addtowishlist=' + pid;
    }  
}

function qvShowAltImage(image)
{
    //alert($(image).attr("path"));
    $(".QVProductImage").attr("src", ProductImagePath + "250/" + $(image).attr("path"));
}

function UpdateQVStockMessage_OnChange(obj){
           
        var pid = $(':selected', obj).val();        
        
        $.ajax({
            url: '/WebServices/Product.asmx/QuickView',
            data: 'pk_pid='+pid,
            type: 'GET',
            dataType: 'xml',
            timeout: 30000,
            error: function(){
                //debug('Error loading document types');
                //UnBlock('.productImage');
            },
            success: function(xml){  
                $(xml).find('results').find('productsizes').each(function(){        
                    
                    var backorderarrivaldate = "";
                    var qtyonhand = 0;
                    var sizeArray = sizeArrayString.split("|");
                    for (var i = 0; i < sizeArray.length; i++)
                    {
                        var sizeResult = sizeArray[i].split("~");    
                        if (sizeResult[0] == pid)
                        {
                            backorderarrivaldate = sizeResult[4];
                            qtyonhand = sizeResult[5];           
                        }
                    }
                           
                    if(qtyonhand != '0' && backorderarrivaldate == '') {                        
                        $("#ltStockMessageSize").hide();                                        		            
                        $(".ltStockMessage","#QuickViewText").text("[In Stock]");                                    
                        //$('.notifyMeLink_'+row).hide();
                    } else if (backorderarrivaldate != '') {
                        $("#ltStockMessageSize").html("Est. ship date " + dateFormat(backorderarrivaldate, 'mm/dd/yyyy')).show();                                        		             
                        $(".ltStockMessage","#QuickViewText").text("[On Backorder]");                                                                      
                    } else {
                        $("#ltStockMessageSize").html('');                                        		            
                    }
                });
            }
        });        
    }    