﻿    var zoomTrigger;
    var index = -1;
    $(document).ready(function(){
        ProductName = escape($('h1', '#ProductDesc').html()).replace("'", "&apos;");
        //alert(ProductName);
        //alert(MarketingIcon);
        //alert(AppTheme); //(/App_Themes/budk.com)
        if(MarketingIcon != '' && MarketingIcon != null) {
            $('img.marketIcon').attr('src', AppTheme + '/MarketingIcons/' + MarketingIcon);
            $('#divMarketingIcons').show();
        }
        /*
        if(MaxQtyPerOrderList != '') {
            $('.maxQtyItems', '#MaxQtyPerOrderListMessage').empty();
            var items = MaxQtyPerOrderList.split('|');
            for(var i = 0; i < MaxQtyPerOrderList.length; i++) {
                var itemPair = items[i].split('&');
                var sku = '';
                var max = '';                
                for(var j = 0; j < itemPair.length; j++) {
                    var tmp = itemPair[j].split('=');
                    
                    if(tmp[0] == 'sku') {
                        sku = tmp[1];
                    } else if(tmp[0] == 'max') {
                        max = tmp[1];
                    }
                }
                alert(sku + ' ' + max);
                
                //$('.maxQtyItems', '#MaxQtyPerOrderListMessage').append('<li>limit of ' + max + ' for ' + sku + ' per order, please choose a quantity that is ' + max + ' or less.</li>');
                //showModal('#MaxQtyPerOrderListMessage','');
            }
        }*/
        
        //init lightbox
        $('.lbTrigger').lightBox();        
        
        if(RestrictedProducts != '') {
            $('ul.removedItems', '#rstshippingmessagepanel').html(RestrictedProducts);
            showModal('#rstshippingmessagepanel', 'Restricted Shipping Notification');
        }
        
        $('.prodThumb').quickview();
        
        document.getElementById('ProductTabs').tabber.tabShow(0);
        //alert(qsPID);
        if(ShowReviewTab == '1') {
            document.getElementById('ProductTabs').tabber.tabShow(1);
        } else {
            $('#'+hfProductIdClientID).val(qsPID);
        }
        
        if(ShowAddReview == '1') {
            $('#WriteReview').show();
        }        
        
        loadStars("0", "normal");
        
        $(".reviewguidelineslink").bind("click", function(e){
            var pos = $(".reviewguidelineslink").offset();
            var style = 'width:600px; height:500px; overflow:scroll; overflow-x:hidden; border:1px solid #555;background-color:#FFF;z-index:99999;cursor:pointer;position:absolute;top:'+(pos.top-100)+'px;left:'+(pos.left-30)+'px;';        
            $('.reveiwguidelinespopup').attr('style', style).show();            
        });    
        $(".reveiwguidelinespopup").bind("mouseleave", function(e){
            $('.reveiwguidelinespopup').hide();
        });
        
        //Pop up the "why shipping restricted" box on mouseover
        $(".whySRlink").bind("click", function(e){
            var pos = $(".whySRlink").offset();            
            var style = 'width:450px; height:300px; overflow-x:hidden; border:1px solid #555;background-color:#FFF;z-index:99999;cursor:pointer;position:absolute;top:'+(pos.top-10)+'px;left:'+(pos.left-86)+'px;';                     
            $('.whySRpopup').attr('style', style).show();            
        });    
        $(".whySRpopup").bind("mouseleave", function(e){
            $('.whySRpopup').hide();
        });    
    });//end doc ready
    
    function SortReviews(sortby) {
        $('#'+SortReviewsId).val(sortby);
        
        $('.hiddenButton').click();
    }
    
    function ThumbClick(pk_pid) {
        //alert(pk_pid);
        $('#'+hfProductIdClientID).val(pk_pid);
        
        AjaxBlock('.productImage');
        
        GrabProduct(pk_pid);
    }

    function GrabProduct(pk_pid) {
        $.ajax({
            url: '/WebServices/Product.asmx/QuickView',
            data: 'pk_pid='+pk_pid,
            type: 'GET',
            dataType: 'xml',
            timeout: 30000,
            error: function(){
                //debug('Error loading document types');
                UnBlock('.productImage', 500);
            },
            success: function(xml){  
                $(xml).find('results').find('product').each(function(){
                    var id = $(this).attr('id');                    
                    var sku = $("sku", this).text();
                    var pName = $("name", this).text();
                    var image = $("imageName", this).text();
                    var sDesc = $("shortDescription", this).text();
                    var longDesc = $("longDescription", this).text();
                    var url = $("seo_url", this).text();
                    var hasZoom = $("hasZoomImage", this).text();
                    var brand = $("brand", this).text();
                    var regPrice = $("regularPrice", this).text();
                    var salePrice = $("salePrice", this).text();
                    var ratingCount = $("ratingCount", this).text();
                    var ratingImage = $("ratingImage", this).text();
                    
                    $('.reviewProductName').html('<strong>' + pName + '</span>');
                    $('#'+hfProductNameClientID).val(pName);
                    
                    $('a.jqzoom', '.productImage').remove();
                    //alert('<%= AppTheme %>');
                    //alert(ProductImagePath);
                    $('div.productImage').prepend('<a href="' + ProductImagePath + '500/' + image.replace(/-/, " ") + '" class="jqzoom"><img class="prodImage" src="' + ProductImagePath + '250/'+ image + '" width="250" height="250" border="0" /></a>');
                    $('h1', '#ProductDesc').html(pName);
                    
                    if(longDesc != null && longDesc != '') {
                        $('.productDescription').html(longDesc);
                    }
                    
		            $(function() {
			            var options =
			            {
				            zoomWidth: 250,
				            zoomHeight: 250,
				            zoomType:'reverse',
				            title :false
			            };
			            $(".jqzoom").jqzoom(options);
		            });
		                    
                    UnBlock('.productImage', 500);
                });
            }
        });    
        
        GrabProductReviews(pk_pid);
    }  
    
    function GrabProductReviews(pk_pid) {
        $('#Reviews').empty();
        $.ajax({
            url: '/WebServices/Product.asmx/GetReviewsXML',
            data: 'pk_pid='+pk_pid,
            type: 'GET',
            dataType: 'xml',
            timeout: 30000,
            error: function(){
                //debug('Error loading document types');
            },
            success: function(xml){  
                var reviewCount = '';
                var reviewAverage = '';
                var reviewStars = '';
                
                $(xml).find('reviews').each(function(){
                    reviewCount = $(this).attr('reviewCount');                    
                    reviewAverage = $(this).attr('averageRating');                    
                    reviewStars = $(this).attr('stars');
                    
                    $('a', '#'+bRatingClientID).html(' ' + reviewCount + ' customer reviews ');
                    $('#'+imgRatingClientID).attr('src', AppTheme + '/graphics/stars/' + reviewStars);
                    $('#'+imgRating1ClientID).attr('src', AppTheme + '/graphics/stars/' + reviewStars);
                });
                
                $(xml).find('reviews').find('review').each(function(){
                    var reviewId = $(this).attr('reviewId');
                    var reviewAddedDate = $('reviewAddedDate', this).text();
                    var reviewApproved = $('reviewApproved', this).text();
                    var reviewBody = $('reviewBody', this).text();
                    var reviewDisplay = $('reviewDisplay', this).text();
                    var reviewEditedDate = $('reviewEditedDate', this).text();
                    var reviewCity = $('reviewCity', this).text();
                    var reviewEmail = $('reviewEmail', this).text();
                    var reviewName = $('reviewName', this).text();
                    var reviewState = $('reviewState', this).text();
                    var reviewScore = $('reviewScore', this).text();
                    var reviewScreenName = $('reviewScreenName', this).text();
                    var reviewSubject = $('reviewSubject', this).text();
                    var reviewUserId = $('reviewUserId', this).text();
                    var reviewState = $('reviewState', this).text();
                    var reviewStar = '';
                    
                    switch (parseInt(reviewScore))
                    {
                        case 1:
                            reviewStar = "stars-1-0.gif";
                            break;
                        case 2:
                            reviewStar = "stars-2-0.gif";
                            break;
                        case 3:
                            reviewStar = "stars-3-0.gif";
                            break;
                        case 4:
                            reviewStar = "stars-4-0.gif";
                            break;
                        case 5:
                            reviewStar = "stars-5-0.gif";
                            break;
                        default:
                            reviewStar = "stars-0-0.gif";
                            break;
                    }                    
                    
			        $('#Reviews').append('<hr class="rev">' +
			        '<div>' +
			        '    <p>' +
			        '        <img src="' + AppTheme + '/graphics/stars/' + reviewStar + '" />&nbsp;-&nbsp;' + dateFormat(reviewAddedDate, 'fullDate') + '<br />' + reviewSubject +
			        '    </p>'+
			        '    <p>' +
			        '        Reviewed By:&nbsp;<strong>' + reviewName + '</strong><br />' + reviewBody +
			        '    </p>' +
			        '</div>');
                });
            }
        });    
    }    
    
    function ShowAlternateImage(img) {
        var image = $(img).attr('imageName');
        //alert(ProductImagePath + '250/'+ image);
        $('a.jqzoom', '.productImage').remove();
        $('div.productImage').prepend('<a href="' + ProductImagePath + '500/' + image.replace(/-/, " ") + '" class="jqzoom"><img class="prodImage" src="' + ProductImagePath + '250/'+ image + '" width="250" height="250" border="0" /></a>');
        $(function() {
            var options =
            {
	            zoomWidth: 250,
	            zoomHeight: 250,
	            zoomType:'reverse',
	            title :false
            };
            $(".jqzoom").jqzoom(options);
        });        
    } 
    
    function UpdateStockMessage_OnChange(obj){
        var pid = $(':selected', obj).val();
        var row = $(obj).attr('row');
        
        $.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('product').each(function(){
                    var id = $(this).attr('id');                    
                    var BOADate = $("BOADate", this).text();
                    var qtyOnHand = $("qtyonhand", this).text();
                    
                    if(qtyOnHand != '0' && BOADate == '') {
                        $('.stockMessage_'+row).html('[In Stock]');                                        		            
                        $('.notifyMeLink_'+row).hide();
                    } else if((qtyOnHand == '' || qtyOnHand == '0') && BOADate == '') {
                        $('.stockMessage_'+row).html('[On Backorder]');                                        		            
                        $('.notifyMeLink_'+row).hide();
                    } else if (BOADate != '') {
                        $('.stockMessage_'+row).html("Estimated ship date " + dateFormat(BOADate, 'm/dd/yyyy'));                                        		            
                        $('.notifyMeLink_'+row).show();
                    } else {
                        $('.stockMessage_'+row).html('');                                        		            
                        $('.notifyMeLink_'+row).hide();
                    }
                });
            }
        });        
    }    
    
    function NotifyMe_OnClick(obj) {
        var pid = $(obj).attr('pid');
        var sku = $(obj).attr('sku');
        var image = $(obj).attr('image');
        var name = $(obj).attr('name');
        
        NotifyMePID = pid;
        
        $('#NotifyMeResults').hide();
        $('#NewUserSignUp').show();
        
        $('.NMProductSKU').html(sku);
        $('.NMProductName').html(name);
        $('.NMProductImage').attr('src', ProductImagePath + '50/' + image);
        
        $("#NotifyMe").css({top:getNotifyMeY(), left:(screen.availWidth/2-240)});                                    
        $("#NotifyMe").fadeIn("slow");        
    }
    
    function CloseNotifyMe() {
        $("#NotifyMe").fadeOut("slow");
        return false;
    }     
    
    function getNotifyMeY() {
        var windowHeight = 0;
        var windowBottom = 0;
        var windowTop = 0;

        if (typeof(window.innerHeight) == 'number') {
	        windowHeight = window.innerHeight;
        }
        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 + 100);
        return y;	
    }    
    
    function nmOptionEmailSignUp_OnChange(obj) {
        var isChecked = $(obj).is(':checked');
        
        if(isChecked) {
            $('.nmStep2').show();            
            $('.hiddenInput', '.nmStep2').removeClass('hidden');
            $('#OptOutMessage').hide();
            $('.notifyMeButton').attr('src', '<%= AppTheme %>/graphics/signupButton.gif');
        } else {
            $('.nmStep2').hide();
            $('.hiddenInput', '.nmStep2').addClass('hidden');
            $('#OptOutMessage').show();
            $('.notifyMeButton').attr('src', '<%= AppTheme %>/graphics/notify_me_btn.gif');
        }    
    }
    
    function nmOptionAll_OnChange(obj) {
        var isChecked = $(obj).is(':checked');
        
        $('input:checkbox', '.nmStep2').each( function(){
            this.checked = isChecked;
        });
    }
    
    function NotifyMeSignUp() {
        var errors = '';
        var interests = '';
        var email = $('.nmEmailAddress', '#NotifyMe').val();
        var emailConfirm = $('.nmEmailAddressConfirm', '#NotifyMe').val();
        //var password = $(':[name=nmPassword]', '#NotifyMe').val();
        var password = '';
        //var passwordConfirm = $(':[name=nmPasswordConfirm]', '#NotifyMe').val();        
        var firstName = $('.nmFirstName', '#NotifyMe').val();
        var lastName = $('.nmLastName', '#NotifyMe').val();
        var state = $('option:selected', '.nmState').val();
        var country = $('option:selected', '.nmCountry').val();
        var emailSignUp = $('.nmOptionEmailSignUp').is(':checked');
        
        AjaxBlock('#NewUserSignUp');
        
        $('input:checkbox', '.nmStep2').not('.nmOptionAll').each( function(){
            if(this.checked) {
                interests += $(this).val() + "|";
            }
        });
        
        if(email != emailConfirm) {
            errors += '<li>Email and Email Confirmation must match</li>';
        }
        
        if(email == '') {
            errors += '<li>Email is required</li>';
        } else {
            if(!ValidateEmail(email)) {
                errors += '<li>Email Address is invalid</li>';    
            }
        }        
        
        if(emailConfirm == '') {
            errors += '<li>Email Confirmation is required</li>';
        } else {
            if(!ValidateEmail(emailConfirm)) {
                errors += '<li>Email Confirmation is invalid</li>';    
            }
        }

//        if(password != passwordConfirm) {
//            errors += '<li>Password and Password Confirmation must match</li>';
//        }
//                
//        if(password == '') {
//            errors += '<li>Password is required</li>';
//        }
//        
//        if(passwordConfirm == '') {
//            errors += '<li>Password Confirmation is required</li>';
//        }
        
        if(emailSignUp) {
            if(firstName == '') {
                errors += '<li>First Name is required</li>';
            }                
            
            if(lastName == '') {
                errors += '<li>Last Name is required</li>';
            }   
            
            if(interests == '') {
                errors += '<li>Interest is required</li>';
            }                     
        } else {
            //empty values so webservice doesnt use them
            firstName = '';
            lastName = '';
            state = '';
            country = '';
            interests = '';
        }
            
        if(errors.length == 0){
            $('ul', '.errors').hide();
            
            if(UserId != '' && UserId != null && UserId != '0') {
                //08-18-09 avc >>signup existing user
                $.ajax({
                    url: '/WebServices/ProductAlerts.asmx/SignUpExistingUser',
                    data: 'pk_pid='+NotifyMePID+'&selectedinterests='+interests+'&emailSignUp='+emailSignUp+'&email='+email,
                    type: 'GET',
                    dataType: 'xml',
                    timeout: 30000,
                    error: function(){
                        //debug('Error loading document types');
                        UnBlock('#NewUserSignUp', 500);
                    },
                    success: function(xml){  
                        $(xml).find('results').each(function() {
                            var alertaddresult = $(this).find('alertaddresult').text();
                            var optinresult = $(this).find('optinresult').text();
                            
                            if(alertaddresult == '') {
                                $('#NewUserSignUp').hide();
                                alertaddresult = '<p>You have successfully signed up for alerts on this product!</p>';
                            }
                            
                            $('.resultText', '#NotifyMeResults').empty().append(alertaddresult + '<br />' + optinresult);
                            $('#NotifyMeResults').show();
                        });
                        
                        UnBlock('#NewUserSignUp', 500);
                    }
                });                
            } else {
                //08-18-09 avc >>create and then signup user
                $.ajax({
                    url: '/WebServices/ProductAlerts.asmx/SignUpNewUser',
                    data: 'pk_pid='+NotifyMePID+'&email='+email+'&password='+password+'&firstname='+firstName+'&lastname='+lastName+'&state='+state+'&country='+country+'&selectedinterests='+interests+'&emailSignUp='+emailSignUp,
                    type: 'GET',
                    dataType: 'xml',
                    timeout: 30000,
                    error: function(){
                        //debug('Error loading document types');
                        UnBlock('#NewUserSignUp', 500);
                    },
                    success: function(xml){  
                        $(xml).find('results').each(function() {
                            var alertaddresult = $(this).find('alertaddresult').text();
                            var optinresult = $(this).find('optinresult').text();
                            
                            if(alertaddresult == '') {
                                $('#NewUserSignUp').hide();
                                alertaddresult = '<p>You have successfully signed up for alerts on this product!</p>';
                            }
                            
                            $('.resultText', '#NotifyMeResults').empty().append(alertaddresult + '<br />' + optinresult);
                            $('#NotifyMeResults').show();
                        });
                        
                        UnBlock('#NewUserSignUp', 500);
                    }
                });                
            }            
        } else {
            $('ul', '.errors').empty().append(errors);
            UnBlock('#NewUserSignUp', 500);
        }
    }
    
    function tb_OnEnter() {
        $('.maxQtyItems', '#MaxQtyPerOrderListMessage').empty();
        
        //check for max qty
        $('input.prodinput').each(function() {
            var qty = $(this).val();
            var maxqty = $(this).attr('maxqty');
            var sku = $(this).attr('sku');
            if(maxqty != null && parseInt(qty) > parseInt(maxqty)) {
                $('.maxQtyItems', '#MaxQtyPerOrderListMessage').append('<li>limit of ' + maxqty + ' for ' + sku + ' per order, please choose a quantity that is ' + maxqty + ' or less.</li>');                
            }
        });
        
        if($('li', '.maxQtyItems').length > 0) {
            showModal('#MaxQtyPerOrderListMessage','');        
            return false;
        } else {
            document.getElementById(ibAddToCartClientID).focus();
            document.getElementById(ibAddToCartClientID).click();        
        }
    } 
    
    function SubmitReview() {
        document.getElementById(btnSubmitClientID).focus();
        document.getElementById(btnSubmitClientID).click();
    }       
    
    function ShowAddReviewTab() {
//        if(IsUserAuthenticated == 'True') {
//            document.getElementById('ProductTabs').tabber.tabShow(1);
//            $('#WriteReview').toggle();
//        } else {
//            document.location = '/login.aspx?addreview=' + '<%= qsPID %>'; 
//        }
        document.getElementById('ProductTabs').tabber.tabShow(1);
    }
    
    function ToggleReviewForm() {
//       if(IsUserAuthenticated == 'True') {
//            document.getElementById('ProductTabs').tabber.tabShow(1);
//            $('#WriteReview').toggle();
//       } else {
//            Boxy.confirm("You must be signed in to add a review.\nTo Sign In click OK.", function(){ 
//                document.location = '/login.aspx?addreview=' + '<%= qsPID %>'; 
//                }
//            , {title: 'Sign In'});
//       }
         $('#WriteReview').toggle();   
    }
    
    function AfterRestrictedItemMessage() {
        Boxy.get('#rstshippingmessagepanel').hide();
        
        if(AddedCnt != '0') {
            document.location = '/cart.aspx';
        }
    }
    
    /* Helper Functions*/    
    function showModal(obj, theTitle) {
      new Boxy(obj, {title:theTitle, modal:true, closeable:false });
    };
    
    function showAlert(obj, theTitle) {
      new Boxy(obj, {title:theTitle, modal:false, closeable:true });
    };        
    /* End Helper Functions */ 