// Graphics images are 1700x690

var animationRunning = true;
var animationItemWidth = 1920;
var animationTimer;
var animationSpeed = 1000;
var animationInterval = 10000;
var animationElements = 0;
var dir = "none";
var isRunning = false;
var itemPos = 1;
var closeSubmenuTimer;
var closePreviewThumb;
var featuredProductsUrl = new Array();
var productExpandedRow = 0;
var productMatrix = "3col";
var categoryFilters = new Array();
var categoryId = 0;
var productOffset = 12; //todo should be 12 here 
var productLimit = 12;
var productOrderBy;
var collectionsArr = new Array();
var queryString='';

var smallW = false;
var largeW = true;
var resizeThreshold = 1196;
var showLoaderMoreProductsBtn = true;
var extractingProducts = false;
var productsRequestCameFrom = "";
var categoryIds = new Array();
var subcategoryId = "";

function getViewportWidth() {
    return jQuery(window).width()
}

function getViewportHeight() {
    return jQuery(window).height()
}

function widthReseter() {
    var newW = getViewportWidth();
    var newH = getViewportHeight();
    
    var p;
    if(newW < resizeThreshold) {
        
        jQuery("#post_4").fadeOut();
        if(jQuery("#banner_4").length){
            jQuery("#banner_4").fadeOut(function(){
                jQuery(".content").width(898)
                jQuery("#footerRight").width(400)
            });
        } else {
            jQuery(".content").width(898)
            jQuery("#footerRight").width(400)
        }
           

        p = (newW - 898 ) / 2
        jQuery(".logo").css({left:p})
        jQuery(".searchPanel").css({right:p})
        jQuery("#shopSubmenu").css({left:-193})

        jQuery("#collectionTitleFrame").css({left:p})

    } else {
        jQuery(".content").width(resizeThreshold)
        jQuery("#post_4").fadeIn();
        jQuery("#banner_4").fadeIn();
        jQuery("#footerRight").width(700)

        p = (newW - resizeThreshold ) / 2
        jQuery(".logo").css({left:p})
        jQuery(".searchPanel").css({right:p})
        jQuery("#shopSubmenu").css({left:0})

        jQuery("#collectionTitleFrame").css({left:p})
    }
    
    //category page - hide last column with items
    if(jQuery("#productList").length == 1) {
        reconfigureProductList(newW);
    }

    // calculate width for collection page
    if(jQuery("#animationCollectionContainer").length) {
        jQuery("#animationCollectionContainer").width(newW);
        jQuery("#collectionAnimation").width(newW * jQuery("#collectionAnimation .item").length);
        jQuery("#collectionAnimation").css({left:scrolled});
        jQuery("#collectionAnimation .item").width(newW);
        
        
        
        jQuery("#animationCollectionContainer").height(newH - 30)
        jQuery("#animationCollectionContainer").height(newH - 30)
        jQuery("#collectionAnimation").height(newH - 30)
        jQuery("#collectionAnimation .item").height(newH - 30) 
    }


    //close minicart if expanded
    closeMiniCart();

}

function openNewsletterModalWindow() {
    jQuery("#newsletterModal input").val('')
    jQuery("#newsletterModal .tooltip").hide();
    jQuery("#newsletterModal .invalidInput").removeClass('invalidInput');
    jQuery("#newsletterModal .checked").removeClass('checked');
    
    jQuery("#monthBirthdate").val('MM')
    jQuery("#dayBirthdate").val('DD')
    jQuery("#yearBirthdate").val('YYYY')
    
    var emailValue = jQuery(".newsletterform #emAddress").val();
    if(emailValue!="ENTER EMAIL FOR NEWS & OFFERS") {
        jQuery("#newsletterModal #emailAddress").val(emailValue);
    }
    //preload the background image
    jQuery("#newsletterModal").fadeIn();
}


function trimAll(sString) {
    while (sString.substring(0,1) == ' ') {
        sString = sString.substring(1, sString.length);
    }

    while (sString.substring(sString.length-1, sString.length) == ' ') {
        sString = sString.substring(0,sString.length-1);
    }

    return (sString);
}

function validateEmail(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test(email) == false) {
      return false;
    } else {
       return true;
   }
}

function submitNewsletterSubscription() {
    //validate inputs
    //check if email address is valid and supplied
    var email = jQuery("#emailAddress").val();
    var msg = "";

    if(trimAll(email) == "") {
        msg = "Email address is required";
    } else {
        if(!validateEmail(email)) {
            msg = "Please make sure your email address is correct.";
        }
    }
 
    if(msg) {
        //show errors and tooltips
        showToolTip("emailAddressLabel",msg,"newsletterModal");
        jQuery("#emailAddress").addClass("invalidInput");

    } else {
           
        jQuery("#newsletterModal .tooltip").hide();
      //  jQuery("#newsletterModal").fadeOut();
        //send data to mail chimp //todo

        var firstName = jQuery("#firstName").val();
        var lastName  = jQuery("#lastName").val();
        var month     = jQuery("#monthBirthdate").val();
        var day       = jQuery("#dayBirthdate").val();
        var year      = jQuery("#yearBirthdate").val();
        
        var special   = 0;
        var tips      = 0;
        var new_products= 0;
        
        if(jQuery('.newsletterModal #special').hasClass('checked')) {
            special = 1;
        }
        
        if(jQuery('.newsletterModal #tips').hasClass('checked')) {
            tips = 1;
        }
        
        if(jQuery('.newsletterModal #new_products').hasClass('checked')) {
            new_products = 1;
        }
        
        jQuery.ajax({
            url     : siteUrl + 'INPINK/account/frontsubscribe/',
            data    : {'FNAME':firstName, 'LNAME':lastName, 'email':email,'birthday':month+'/'+day+'/'+year,'special':special,'new_products':new_products,'tips':tips},
            type    : 'POST',
            dataType: 'JSON',
            async: true,
            success : function(response) {
                if(response.succes == true) {
                    showToolTip("emailAddressLabel",'Thank you, you\'ve successfully been added to our email list.',"newsletterModal");
                    setTimeout('closeNewsletterModalWindow()',4000);
                    jQuery(".footer #emAddress").val('ENTER EMAIL FOR NEWS & OFFERS')
                } else {
                    showToolTip("emailAddressLabel",response.msg,"newsletterModal");
                    jQuery("#emailAddress").addClass("invalidInput");
                }
            }
        })
        
    }
}

function closeNewsletterModalWindow() {
    jQuery("#newsletterModal .tooltip").hide();
    jQuery("#newsletterModal").fadeOut();
}


function showToolTip(elemId,tooltipMsg,container) {
    var elem = jQuery("#" + elemId);
    var pos = jQuery(elem).position();

    if(jQuery("#"+container + ' #tooltip_' + elemId).length == 0) {
        jQuery("#"+container).append("<div id='tooltip_"+elemId+"' class='tooltip'><div class='top'></div><div class='body'></div><div class='bottom'></div></div>");
    }
    jQuery("#tooltip_" + elemId + " .body").html(tooltipMsg);
    jQuery("#tooltip_" + elemId).css({left:(elem.width() / 2)* -1,top:pos.top + 50}).fadeIn();
}

function closeMiniCart() {
    jQuery("#minicart").fadeOut();
}

function openMiniCart() {
    var p = jQuery("#minicartBtn").offset();
    jQuery("#minicart").css({left:p.left - 75,top:88})
    jQuery("#minicart").fadeIn(200);

    //activate hover functionality
    jQuery("#minicart .cartThumb").hover(
        function(){
            jQuery(this).find(".ovr").fadeIn(200);
        },
        function(){
            jQuery(this).find(".ovr").fadeOut(200);
        }
    )
    //initiate close event
    jQuery(".closeMiniCart").click(function(){
        closeMiniCart();
    })

}


function reconfigureProductList(w,forceReconfigure) {
    var newProdMatrix = "";
    productExpandedRow = 0;
    if(w < resizeThreshold) {
        newProdMatrix = "2col";
        jQuery(".productList").width(596);
        jQuery("#toolbar").width(596);
        jQuery(".content").width(898);
        jQuery("#footerRight").width(400)
        jQuery(".loaderButtons").width(600)

    } else {
        newProdMatrix = "3col";
        jQuery(".productList").width(894);
        jQuery("#toolbar").width(894);
        jQuery(".content").width(resizeThreshold);
        jQuery("#footerRight").width(700)
        jQuery(".loaderButtons").width(898)

        //products 3 columns
    }

    if(productMatrix != newProdMatrix || forceReconfigure) {
        jQuery("#productList .item").height(336)
        productMatrix = newProdMatrix;
        var i = 0;
        var r = 1;
        var prevIdx;

        if(productMatrix == '2col') {
            i=0;
            r = 1;
            jQuery("#productList .item").each(function(){
                i++;
                prevIdx = jQuery(this).attr("row")
                jQuery(this).attr("row",r).removeClass("row" + prevIdx).addClass("row" + r);
                if(i%2 == 0) {
                    //impar
                    r++;
                }
            })

        } else {

            i=0;
            r = 1;
            jQuery("#productList .item").each(function(){
                i++;
                prevIdx = jQuery(this).attr("row")
                jQuery(this).attr("row",r).removeClass("row" + prevIdx).addClass("row" + r);
                if(i == 3) {
                    r++;
                    i=0;
                }
            })

        }
    }

}

function extractProducts(liveLoading,showAllProducts,loadMore,resetOffest) {
    /*
     * this is used in app/design/default/inpink/template/catalog/category/view.phtml
     * sent current filters to server, current offset and an amount of products that should be extracted from db     *
     **/
    productsRequestCameFrom = 'filters';
    if(extractingProducts) return;
    
    extractingProducts = true;
    
    
    //productOffset = 0;    
    //override the above detection.
    if(window.location.hash=="" || window.location.hash == "#") {
	//productLimit = 12
    }
        
    
    if(!liveLoading){
        showPreloader();
    }
  
    if(!liveLoading && (window.location.hash=="" || window.location.hash == "#") ) {
        productLimit = 12; 
      //  productOffset = 0;    
    } 
    
    if(resetOffest) {
        productOffset = 0;
        productLimit = 12
    }
    
    
    if(loadMore) {
       // productOffset = 0;
        if(productLimit == 10000) {
             productLimit = 12
        }
        productOffset += productLimit
    }

    if(showAllProducts) {
        productOffset = 0;    
        productLimit = 10000
    }
    
   
    var priceFilterSelected = '';
  //  var cId = categoryId;
    for(i=0;i<categoryFilters.length;i++) {
        if(categoryFilters[i]) {
            var x = categoryFilters[i].split('|')
            if(x[0]=="Type") {
//                cId = x[1];
                categoryFilters[i] = null
                delete(categoryFilters[i])
            } 
            if(x[0] == "price") {
                priceFilterSelected = x[1] 
            }
            
        } else {
            delete(categoryFilters[i])
        }
    }
    var childsCategoriesIds = categoryIds.join(","); //deprecated ?
    var filtersString = categoryFilters.join('-');
    
    
    var priceFiltersIds = new Array();
    
    jQuery("#group_price li").each(function(){
        priceFiltersIds[priceFiltersIds.length] = jQuery(this).attr('id');
    })
    
    var priceFiltersIdsString = priceFiltersIds.join("|");
    
    
    
    
    
    jQuery.ajax({
            url     : siteUrl + 'INPINK/json/category/',
            data    : ({categoryId:categoryId, limit:productLimit, offset:productOffset,filters:filtersString,orderBy:productOrderBy,queryString:queryString,subcategs:subcategoryId,priceIds:priceFiltersIdsString}),
            type    : 'POST',
            dataType: 'JSON',
            async: true,
            beforeSend: function() {if(loadMore){/*alert(productLimit);alert(productOffset);productOffset += productLimit;alert(productOffset)*/}},
            success : function(data) {
                
                addHashFilter({categoryId:categoryId, limit:productLimit, offset:productOffset,filters:filtersString,orderBy:productOrderBy,queryString:queryString,subcategs:subcategoryId,priceIds:priceFiltersIdsString})
                
                //productOffset += productLimit
                
                //var response = eval('(' + data + ')');
                var resultsStatus = '';
                var response = data
                
                if(response.count == 1) {
                    resultsStatus = '1 RESULT';
                } else {
                    resultsStatus = response.count+' RESULTS';
                }
                
                jQuery("#cntProds").html(resultsStatus);
                
                
                var newRow = '';
            
                jQuery.each(response.items,function(a,prod){
                
                    newRow += '<div class="item">';
                    newRow += '<div class="pics">';
                    
                    for(i=0;i<2;i++) {
                        if(prod.images[i]) {
                            newRow += '<a href="'+siteUrl+prod.url_path+'"><img src="'+prod.images[i]+'" alt="" /></a>';
                        }    
                    }
                    
                    newRow += '</div>';
                    newRow += '<div class="itemInfo">';
                    newRow += '<div><a href="'+siteUrl+prod.url_path+'">'+prod.name+'</a></div>';
                    newRow += '<div>$'+prod.price+'&nbsp;&nbsp;';
                    
                    if(prod.embeded_media) {
                        newRow += '<a href="javascript:void(0)" onclick="openVideo(\''+prod.name+' '+ '$'+prod.price+'\',\''+prod.embeded_media+'\'); ">';
                        newRow += '<img src="'+videoIcon+'" alt="" />';
                        newRow += '</a>';
                    }
                    
                    newRow += '</div>';
                    
                    newRow += '</div>';
                    newRow += '</div>';
                    
                 })
             
                if(liveLoading) {
                    jQuery("#productList").append(newRow)    
                } else {
                    jQuery("#productList").html(newRow)    
                }
                 
                 var newW = getViewportWidth();
                 reconfigureProductList(newW,true);
                 runHoverAnimation();
                 
                 //update filters
                // jQuery('.filter .inactive').removeClass("inactive")
                 
                 if(response.new_filters) {
                    jQuery.each(response.new_filters,function(idx,filter){
                        jQuery("#" + filter.filterName).html(filter.txt);
                        
                        var responseFilters = filter.filterName.split("_");
                        
                        if(filter.cnt == 0) {
                           jQuery("#" + filter.filterName).addClass('inactive');                    
                        } else {
                            jQuery("#" + filter.filterName).removeClass('inactive');                    
                        } 
                        
                        if(responseFilters[1]=="Type") {
                            if(subcategoryId) {
                                jQuery("#" + filter.filterName).addClass('inactive');
                            } else {
                                if(filter.cnt == 0) {
                                    jQuery("#" + filter.filterName).addClass('inactive');
                                } else {
                                    jQuery("#" + filter.filterName).removeClass('inactive');
                                }
                            }
                            
                            
                        }
                     })
                     
                     
                     
                 }
                 
                 if(response.count < productOffset) {
                    jQuery('#productLoader #loaderBtn').show();
                    jQuery('#productLoader #loaderAnimation').hide();
                    jQuery('#productLoader').show();
                    
                    jQuery('#productLoaderAllProducts #loaderBtn').show();
                    jQuery('#productLoaderAllProducts #loaderAnimation').hide();
                    jQuery('#productLoaderAllProducts').show();
                    
                 } else {
                    jQuery('#productLoader #loaderBtn').hide();
                    jQuery('#productLoader #loaderAnimation').hide();
                    jQuery('#productLoader').hide();
                   
                    jQuery('#productLoaderAllProducts #loaderBtn').hide();
                    jQuery('#productLoaderAllProducts #loaderAnimation').hide();
                    jQuery('#productLoaderAllProducts').hide();
                   
                 }
                 
                 
                // Selerum - KL : 20120117 - Always show ""Load All"" button for now.
                jQuery('#productLoaderAllProducts #loaderBtn').show();
                jQuery('#productLoaderAllProducts').show();
                 
                 
                 
                 if(!liveLoading) {
                  hidePreloader();  
                 } 
                 
                 extractingProducts = false;
            }
        })
    
}

function runHoverAnimation() { 
    //category - hover on items
    jQuery("#productList .item").hover(
        function(){
            /*
            if(jQuery(this).find(".pics a").length > 1) {
                jQuery(this).find(".pics").animate({left:-294})
            }
            */
            var rowIdx = jQuery(this).attr('row');

            if(rowIdx == productExpandedRow) {
                return false;
            } else {
                jQuery(".row" + productExpandedRow).animate({height:336},250);
            }

            jQuery(".row" + rowIdx).animate({height:398},250);
            productExpandedRow = rowIdx;
           
//            jQuery(this).find('.pics a').last().fadeOut();
           
            //jQuery('#productList .item .pics a').last().fadeOut()
        },
        function(){
            
          //  jQuery(this).find(".pics").animate({left:0})
        }
    )
        
        if(categoryId!=46) {
            jQuery('#productList .item .pics').hover(function(){
                var justRun = 0;
                jQuery(this).find('img').each(function(){
                    var src = jQuery(this).attr('src');
                    var srcParts = src.split('/');
                    if(srcParts[srcParts.length - 1] != "categoryNoPicture.png") {
                        justRun++ ;
                    }
                    
                })
//                
//                if(justRun == false || jQuery(this).find('img').length < 2) {
//                    return false;
//                }
                
                if(justRun == 2) {
                    jQuery(this).find('a').last().fadeOut(600)
                }
            },
            function(){
                jQuery(this).find('a').last().fadeIn(250)
            })
        }
        
}

function showPreloader() {
    var w = jQuery(".productList").width();
    var h = jQuery(".productList").height();
    
    jQuery("#preloader").width(w + 4).height(h - 158).fadeIn();
}

function hidePreloader() {
    jQuery("#preloader").fadeOut();
}

//open video modal
function openVideo(modalTitle,embededCode) {

//  var videoPlayer = '<iframe src="http://player.vimeo.com/video/' + embededCode + '" width="639" height="360" frameborder="0"></iframe>'; //vimeo
    var videoPlayer = '<iframe title="YouTube video player" width="639" height="360" src="http://www.youtube.com/embed/' + embededCode + '" frameborder="0"></iframe>'; //youtube

    jQuery("#videoModal .modalContent").html("<h1>" + modalTitle + "</h1>" + videoPlayer);
    jQuery("#videoModal").modal();
}

// open video modal with an youtube player (all inpink videos are embeded into player's playlist)
function playAllVideos() {
    //opens a modal window and a youtube player with all inpink videos embeded
    jQuery("#allVideosModal").modal();
}

function updateCollectionInfo(collection) {

    //show collection's name
    jQuery("#collectionTitleFrame .title").html( collection.name + " COLLECTION")
    var w = jQuery("#collectionAnimation .item").first().width();
    
    var pos = w * i * -1;
    jQuery("#collectionAnimation").css({"left":pos})

    // make link
    jQuery("#collectionTitleFrame .shopBtn a").click(function(e){
        location.href = collection.url;
        e.stopPropagation();
    })

    //show price
    jQuery("#collectionTitleFrame .price").html("$" + collection.price);

    //promo discount
    jQuery("#collectionTitleFrame .saveAmount").html("save <br />$" + collection.savings); // todo TBD

    //show video icon is embeded media is attached
    if(collection.video) {
        jQuery("#collectionTitleFrame .videoIcon").show();
        jQuery("#collectionTitleFrame .videoIcon img").click(function(e){
            openVideo(collection.name,collection.video)
            e.stopPropagation();
        })
    } else {
        jQuery("#collectionTitleFrame .videoIcon").hide();
    }
}

//init fancy dropdown // deprecated !?
function fancyDropDown(className) {
    jQuery('.' + className).hyjack_select(
        {// Defaults
            ddImage: siteUrl + 'skin/frontend/default/inpink/images/arrow-down-select.jpg',// arrow_down.png
            ddCancel: '',    // cancel.png
            ddImageClass: 'class_of_arrow',     // hjsel_ddImage
            ddCancelClass: 'class_of_cancel',   // hjsel_ddCancel
            emptyMessage: 'No item available',   // No Items to Display
            restrictSearch: false/true,         // false
            fixedWidth:true,
            offset: 12           // false
        }
    )
}


//on load scripts
jQuery(document).ready(function(){
  
  widthReseter();
  
  //SELERUM-KL : Show nav and main content before sliders finish loading.
    jQuery('.logo').css('visibility', 'visible')
    jQuery('.searchPanel').css('visibility', 'visible')
    jQuery('.content').show();
    
    jQuery(".logo").mousemove(function(e){
    jQuery('#rightArrow').hide();
    jQuery('#leftArrow').hide();
    e.stopPropagation();
  }).click(function(e){e.stopPropagation();})

 jQuery(".searchPanel").mousemove(function(e){
    jQuery('#rightArrow').hide();
    jQuery('#leftArrow').hide();
    e.stopPropagation();
 }).click(function(e){e.stopPropagation();})


//event tracking
//chat link
jQuery('#chatLink').click(function(){
	trackGAEvent('Stylist', 'Click', 'Chat');	
});

//add to wishlist
jQuery('#aWishlist').click(function(){
	trackGAEvent('Wishlists', 'Click', 'Add to Wishlist');	
});

//add tag
jQuery('.addTag').click(function(){
	trackGAEvent('Tags', 'Add', 'New Tag');	
});

//play video - PDP
jQuery('#popenVideo').click(function(){
	trackGAEvent('Image Merchandising ', 'Play', 'Product Video');	
});

//play video - CDP
jQuery('#copenVideo').click(function(){
	trackGAEvent('Image Merchandising ', 'Play', 'Collection Video');	
});

//add to wishlist
jQuery('.searchWishlistBtn').click(function(){
	trackGAEvent('Wishlists', 'Search', 'Searched Someone\'s Wishlist');
});

//blog recomended
jQuery('.fb_edge_widget_with_comment').click(function(){
	//alert('asdf');
	//trackGAEvent('Recommendations', 'Click', 'From Blog');	 
	//return false;
});

jQuery('.detailedBlog #shareIcons .twitter').click(function(){
	trackGAEvent('Share', 'Twitter', 'Blog');
});
jQuery('.detailedBlog #shareIcons .facebook').click(function(){
	trackGAEvent('Share', 'Facebook', 'Blog');
});
jQuery('.detailedBlog #shareIcons .email').click(function(){
	trackGAEvent('Share', 'Email', 'Blog');
});


//PDP recomended
jQuery('#main #shareIcons a').click(function(){
	trackGAEvent('Recommendations', 'Click', 'From PDP');	
});

jQuery('#main #shareIcons .twitter').click(function(){
	trackGAEvent('Share', 'Twitter', 'PDP');
});
jQuery('#main #shareIcons .facebook').click(function(){
	trackGAEvent('Share', 'Facebook', 'PDP');
});
jQuery('#main #shareIcons .email').click(function(){
	trackGAEvent('Share', 'Email', 'PDP');
});


//Dear Pink recomended
jQuery('#faqList .relatedItems a').click(function(){
	trackGAEvent('Recommendations', 'Click', 'From Dear Pink');	
});

//see item in collection
jQuery('.purchaseSep a').click(function(){
	trackGAEvent('Recommendations', 'Click', 'Item in Collection');	
});

//add to cart from wishlist
jQuery('.wishlist-btn-cart').click(function(){
	trackGAEvent('Recommendations', 'Click', 'Wishlist Suggestion');	
});

//homepage banners
jQuery('.banners #banner_1 a').click(function(){
	trackGAEvent('Banners', 'Click', 'Banner 1');	
});
jQuery('.banners #banner_2 a').click(function(){
	trackGAEvent('Banners', 'Click', 'Banner 2');	
});
jQuery('.banners #banner_3 a').click(function(){
	trackGAEvent('Banners', 'Click', 'Banner 3');	
});
jQuery('.banners #banner_4 a').click(function(){
	trackGAEvent('Banners', 'Click', 'Banner 4');	
});

//cart banners
jQuery('.hints .hint-gift').click(function(){
	trackGAEvent('Banners', 'Click', 'Cart Banner 1 ');	
});

// image merchandising view 1
var th1 = jQuery("#product-images .small-images img")[0];
jQuery(th1).click(function(){    
        trackGAEvent('Image Merchandising', 'Click', 'View 1');
});

// image merchandising view 2
var th2 = jQuery("#product-images .small-images img")[1];
jQuery(th2).click(function(){    
        trackGAEvent('Image Merchandising', 'Click', 'View 2');
});

// Category: Image Merchandising - zoom
jQuery("#product-images .scoop").click(function(){    
        trackGAEvent('Image Merchandising', 'Click', 'Zoom');
});

// Recently Viewed Items from Cart Page
jQuery(".cart .recentlyViewed .recom-thumb").click(function(){
	trackGAEvent('Recommendations', 'Click', 'Recently Viewed');	
});

// Recommended Product from Cart Page
jQuery(".cart .recentlyViewedRight .recom-thumb").click(function(){
	trackGAEvent('Recommendations', 'Click', 'From Cart');	
});

// Added a product to cart from Someone's Wishlist - to track added items from
// wishlist mail a parameter is being sent to add to cart controller -> which forwards it to view
// -> which sends the request to GA.
jQuery(".wishlist-page .wishlist-btn-cart").click(function(){
	trackGAEvent('Wishlists', 'Add', 'From Searched Wishlist');	
});

// PDP Recommended Product
var polish = jQuery(".bottom-box .white-holder-product")[1];
jQuery(polish).click(function(){    
        trackGAEvent('Recommendations', 'Click', 'PDP Polish');
});

// FUNNEL 1. LOGGIN - checkout login button
jQuery(".checkoutStepsContainer #send2").click(function(){
        trackGAFunnel(1);
});

    //modal newsletter scripts
    jQuery("#newsletterModal .checkbox").click(function(){
        if(jQuery(this).hasClass("checked")) {
            jQuery(this).removeClass("checked");
        } else {
            jQuery(this).addClass("checked");
        }
    })

    //open newsletter modal window
    jQuery(".submitNewsletter").click(function(e){
        openNewsletterModalWindow();
        e.stopPropagation();
    })
  
    //close newsletter modal window and other popup windows
    jQuery("body").click(function(){
        
        jQuery("#newsletterModal").fadeOut();
        closeMiniCart()
    })

    jQuery("#newsletterModal").click(function(e){
        e.stopPropagation();
    })

    //filter expander
    jQuery(".filterBox .filterTitle").click(function(){
        var parent = jQuery(this).parent();

        if(parent.hasClass("expanded")) {
            parent.removeClass("expanded")
            parent.find(".filterList").slideUp(100)
        } else {
            parent.addClass("expanded")
            parent.find(".filterList").slideDown()
        }
    })

    //clear all filters
    jQuery(".clearFilters").click(function(e){
        window.location.hash = '';
        window.location.reload();
        e.stopPropagation();
    })

    //add or remove filter item
    jQuery(".itemList li").click(function(){
        if(jQuery(this).hasClass('inactive') && !jQuery(this).hasClass('selected')) return false;

        var parent = jQuery(this).parents().filter("div.filterBox").attr("id");
        var filterName = jQuery("#" + parent + " .filterTitle").html();

        var itemName = jQuery(this).html().split(" (");
        var itemId = jQuery(this).attr("id");

        //add to js variables //todo
        if(jQuery(this).hasClass('selected')) {
            //remove from current filter box
            //console.log('des')
            jQuery("#selected_" + itemId).fadeOut(function(){jQuery(this).remove()});
            jQuery(this).parent().find('li').removeClass('inactive')
            jQuery(this).removeClass('selected')
            var id = jQuery(this).attr('id');
            
            if(id == 'f_Type_' + subcategoryId) {
                subcategoryId = "";
            }
            
            //remove from filters
            
            categoryFilters = new Array();

            categoryIds = new Array();
            
            jQuery(".itemList .selected").each(function(){
                var newFilterId = jQuery(this).attr('id')
                var fp = newFilterId.split("_");
             //   categoryFilters[categoryFilters.length] = fp[1] + "|" + fp[2];
                
                if(fp[1] == "price") {
                    categoryFilters[categoryFilters.length] = fp[1] + "|" + fp[2]+","+fp[3];
                    
                    jQuery("#typePrice li").addClass('inactive');
                    jQuery("#f_price_" + fp[2]+"_"+fp[3]).addClass('selected');     
                    
                } else {
                    categoryFilters[categoryFilters.length] = fp[1] + "|" + fp[2];
                }
                
                if(fp[1] == "Type") {
                    //categoryIds[categoryIds.length] = fp[2];
                    subcategoryId = "";
                    
                }
                
                console.log("unselect===="+subcategoryId)
                console.log(fp)
            })
            
        } else {
            
            //add to current filter box
            jQuery("#currentFilters .list").append("<li id='selected_" + itemId.replace(',','') +"'>" + filterName + " " + itemName[0] + "</li>");
            jQuery(this).addClass('selected')

            //make the remaining filters inactive
            jQuery(this).parent().find("li").addClass('inactive');
            jQuery(this).removeClass('inactive');
            
            var filterParts = itemId.split("_");
            //categoryFilters[categoryFilters.length] = filterParts[1] + "|" + filterParts[2];
            
            if(filterParts[1] == "price") {
                categoryFilters[categoryFilters.length] = filterParts[1] + "|" + filterParts[2]+","+filterParts[3];
            } else {
                categoryFilters[categoryFilters.length] = filterParts[1] + "|" + filterParts[2];
            }
            
            if(filterParts[1] == "Type") {
               categoryIds[categoryIds.length] = filterParts[2];
               subcategoryId = filterParts[2];
               console.log("subcategoryId = " + subcategoryId)
            }
            // make the clear button visible
            jQuery("#clearAllButton").css("display","inline");
        }

        //productOffset = 0;
        //productLimit = 18;

        //extract products that match the selected filters
        //extractProducts();
        extractProducts(false,false,false,true)
        
    })

    //close minicart window
    jQuery(".searchPanel .cartBtn").hover(function(){
        openMiniCart();
    })

    jQuery("#collectionTitleFrame").click(function(e){
        e.stopPropagation();
    })

    jQuery("#minicart").click(function(e){
        e.stopPropagation();
    })

    
    //reset the animation items for new window sizes
    jQuery(window).resize(function(){
        widthReseter();
        
        //custom resize event resizeThreshold
        registerSmallWindowEvent();
        registerLargeWindowEvent();
        
    });
    
    //listen to the custom event - demo
    //jQuery('body').bind('smallWindow', function(){console.log('help, window is too small!!!')});
    //jQuery('body').bind('largeWindow', function(){console.log('saved, window is large again!!!')});
    
    // trigger the small window event at startup also;
    //registerSmallWindowEvent();
    setWidthCookie();
    
    
    jQuery("#minicart").hover(
        function (){
        },
        function(){
            closeMiniCart();
        }
    )
})


function setWidthCookie(){
    if(readCookie('windowWidth') == null || readCookie('windowWidth') != jQuery(window).width()){
        createCookie('windowWidth', jQuery(window).width(), 3);
    }
}

function registerSmallWindowEvent(){
    
    //console.log('scripts.js: this triggers the window with checker');
    if( !smallW && jQuery(window).width() < resizeThreshold){
        smallW = true;
        largeW = false;
        //console.log('scripts.js: this triggers actual smallWindow event. Debug here.');
        jQuery('body').trigger('smallWindow');
    }
}

function registerLargeWindowEvent(){
    if( !largeW && jQuery(window).width() >= resizeThreshold){
        largeW = true;
        smallW = false;
        jQuery('body').trigger('largeWindow');
    }
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function isValidPostalCode(postalCode, countryCode) {
    switch (countryCode) {
        case "US":
            postalCodeRegex = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
            break;
        case "CA":
            postalCodeRegex = /^([A-Z][0-9][A-Z])\s*([0-9][A-Z][0-9])$/;
            break;
        default:
            postalCodeRegex = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    }
    return postalCodeRegex.test(postalCode);
}



function showSuccessMsg(message, selector)
{
        resetStatusMsg()
        msg = '<ul><li>'+message+'</li></ul>';
        jQuery('.msgs .error-msg').html(msg);
        jQuery(selector).prepend(jQuery('.msgs'));
        jQuery('.msgs').show();
}

function showErrorMsg(message, selector)
{
        resetStatusMsg();
        msg = '<ul><li>'+message+'</li></ul>';
        jQuery('.msgs .error-msg').html(msg);
        jQuery(selector).prepend(jQuery('.msgs'));
        jQuery('.msgs').show();
}

function resetStatusMsg()
{
        jQuery('.msgs').hide();
}

function trackGAEvent(category, action, label){
	_gaq.push(['_trackEvent', category, action, label]);
}

function trackGAFunnel(step)
{
    var destination = "";
    switch (step)
    {
        case 1: //1. LOGGIN - checkout login button
            destination = '/checkout/onepage/login.html';
            break;
        case 2: //2. BILLING ADDRESS - continue button
            destination = '/checkout/onepage/billing-address.html';
            break;
        case 3: //3. SHIPPING INFO - continue button
            destination = '/checkout/onepage/shipping-info.html';
            break;
        case 4: //4. SHIPPING METHOD - continue button
            destination = '/checkout/onepage/shipping-method.html';
            break;
        case 5: //5. PAYMENT INFO - continue button
            destination = '/checkout/onepage/payment-info.html';
            break;      
        case 6: //6. REVIEW SUBMIT - place order button
            destination = '/checkout/onepage/success';
            break; 
        default:
            break      
    }
    
    _gaq.push(['_trackPageview', destination]);
}





var forbidenStatesIds = new Array();
    forbidenStatesIds[20] = 20; //GUAM
    //forbidenStatesIds[21] = 21; //Hawaii
    //forbidenStatesIds[2] = 2; //Alaska
    forbidenStatesIds[52] = 52; //Puerto Rico
    forbidenStatesIds[60] = 60; //Virgin Islands
    forbidenStatesIds[6] = 6; //Armed forces ,,
    forbidenStatesIds[7] = 7; //Armed forces ,,
    forbidenStatesIds[8] = 8; //Armed forces ,,
    forbidenStatesIds[9] = 9; //Armed forces ,,
    forbidenStatesIds[10] = 10; //Armed forces ,,
    forbidenStatesIds[11] = 11; //Armed forces ,,

var selectedRegion = 0;
var selectedRegionValue = '';
   function removePoBoxRegions(container,countryId,regionId,act,selectorClassName,selectorName,selectorId,doNotSaveAddressFlag,preserverSelectedValue) {
       
       if(selectedRegion == 0) {
           selectedRegion = regionId
       } 
       
       if(countryId == '') {
           countryId = "US";
       }
       
       if(act == "check") {
           jQuery("#shipping_is_po_box").val(1)
       } else {
           jQuery("#shipping_is_po_box").val(0)
       }
   
   
                var s = jQuery('<select id="'+selectorId+'" name="'+selectorName+'" class="validate-select '+selectorClassName+'">');
                op = jQuery('<option value=""></option>');
                op.appendTo(s);
                
                jQuery.each(countryRegions[countryId], function(i, item){
                   if(act == "check" && forbidenStatesIds[i] !== undefined) {
                       return;
                   } else {
                       
                       if((regionId == i && act != "check" && selectedRegion == 0) || (selectedRegion == i)) {
                           op = jQuery('<option value="'+ i +'" selected="selected" rel="sel">'+ item.name +'</option>');
                       } else {
                           op = jQuery('<option value="'+ i +'">'+ item.name +'</option>');
                       }
                   }

                    op.appendTo(s);
                    //jQuery('.chkRegion').selectbox();
                });
                jQuery('#' + container).html(s);



                jQuery('#'+selectorId).selectbox({
                    effect: "fade",
                    optionPosition: 24,
                    bottomElem: true,
                    onChange: function(value, inst){
                        selectedRegion = value
                        if(!doNotSaveAddressFlag) {
                            saveShippingAddressInAddressBook()
                        }
                            
                        //visually select the clicked item
                        jQuery('.sbOptions a[class=selected]').removeClass('selected');
                        jQuery('.sbOptions a[rel='+ value +']').addClass('selected');
                    }
                });
   
}




function regionSelector(container,selectorId,selectorName,countryId,regionId,selectorClass,PoBoxId,appendCheckoutFunction) {
    var act;
    if(jQuery("#"+PoBoxId).attr('checked') == true) {
        act = "check";
    } else {
        act = "uncheck";
    }
    
    if(countryId=="") {
        countryId = 'US';
    }
    
    var s = jQuery('<select id="'+selectorId+'" name="'+selectorName+'" class="validate-select '+selectorClass+'">');
    var op;
    
    op = jQuery('<option value=""></option>');
    op.appendTo(s);

    //data source
    jQuery.each(countryRegions[countryId], function(i, item){
        if(act == "check" && forbidenStatesIds[i] !== undefined) {
            return;
        } else {
            if(regionId == i) {
                op = jQuery('<option value="'+ i +'" selected="selected" rel="sel">'+ item.name +'</option>');
            } else {
                op = jQuery('<option value="'+ i +'">'+ item.name +'</option>');
            }
            op.appendTo(s);
        }
    });
    
    jQuery('#' + container).html(s);
    
    
    
    if(selectorId == 'shipping:region_id') {
        jQuery('.'+selectorClass).selectbox({
            effect: "fade",
            optionPosition: 24,
            bottomElem: true,
            onChange: function(value, inst){
                jQuery('.sbOptions a[class=selected]').removeClass('selected');
                jQuery('.sbOptions a[rel='+ value +']').addClass('selected');

                if(appendCheckoutFunction) {
                    saveShippingAddressInAddressBook();
                }

            }
        });
    } else {
        jQuery('#'+selectorId).selectbox({
            effect: "fade",
            optionPosition: 24,
            bottomElem: true,
            onChange: function(value, inst){
                jQuery('.sbOptions a[class=selected]').removeClass('selected');
                jQuery('.sbOptions a[rel='+ value +']').addClass('selected');

                if(appendCheckoutFunction) {
                    saveShippingAddressInAddressBook();
                }

            }
        });
    }
}

jQuery(window).load(function(){
    widthReseter();
    registerSmallWindowEvent();
    
    //show the main container
    jQuery('.content').show();
    
    jQuery('.logo').css('visibility', 'visible')
    jQuery('.searchPanel').css('visibility', 'visible')
    
    jQuery('body').trigger('afterResize');
    
});


