
jQuery(document).ready(function(){
/*
    jQuery('.add-tag').click(function(){
        var that = jQuery(this);
        jQuery.ajax({
        url     : siteUrl + 'inpink/tag/save/product/' + that.parent().find('.productIdForTag').val() + '?productTagName=' + that.parents('.addTagPopup').find('.tagName').val(),
        type    : 'GET',
        dataType: 'json',
        success : function(data) {
            //data = eval(data);
            if(data.success) that.parents('.addTagPopup').fadeOut();
        }
    });
        
    });  

    
    jQuery('.addTag').click(function(){
        jQuery(this).next().find("input[class!=productIdForTag]").val('')
        jQuery(this).next().find("textarea").val('')
        jQuery(this).next().fadeIn();    
    });
    
    */
    
    jQuery('.closeTagForm').click(function(){
        jQuery(this).parents('.addTagPopup').fadeOut();
    });
    
});

function enlargeThumb(path,imageContainer, bigPath) {

    jQuery("#"+imageContainer+" #image").attr('src',path);
    jQuery("#"+imageContainer+" #image").attr('rel',bigPath);
    //jQuery('img.panning').attr("src", bigPath);
    currentImage = bigPath;
    //console.log(bigPath);
}

// add product in mini-cart (fly into cart animation)
function addToCart(prodId, qty) {
    //todo add into cart
    
    if(qty == undefined || qty == ''){
        var qty = jQuery("#qty").val();
    } 
    var product_id = null;
    
    if(prodId == undefined || prodId == ''){
        product_id = jQuery("#productId").val();
    } else 
        product_id = prodId;

    var optionName = jQuery(".super-attribute-select").attr("name")
    var optionValue = jQuery(".super-attribute-select").val()

    if(jQuery("#wishlist-btn-cart-" + product_id).length) {
        jQuery("#wishlist-btn-cart-" + product_id).hide();
        jQuery("#wishlist-btn-cart-" + product_id).parent().append('<img src="'+fontSiteUrl+'skin/frontend/default/inpink/images/opc-ajax-loader.gif" />')
        
        //search for special attributes (configurable products)
        optionName = jQuery("#whishlistProd-"+product_id).find(".super_attribute").attr("name")
        optionValue = jQuery("#whishlistProd-"+product_id).find(".super_attribute").val()
    }
    
    if(optionName!=undefined && (optionValue == undefined || optionValue == "") ) {
        //hide loader for wishlist items
        jQuery("#wishlist-btn-cart-" + product_id).parent().find('img').remove();
        jQuery("#wishlist-btn-cart-" + product_id).show()
        
        alert("Please select an option.");
        return ;
    }
    jQuery('.addToCartBtn').addClass('btnWait');   
    jQuery.ajax({
        url     : siteUrl + 'checkout/cart/add/product/' + product_id + '/?' + optionName + '=' + optionValue + '&qty=' + qty,
        type    : 'GET',
        //dataType: 'JSON',
        async: false,
        success : function(data) {
            
            
            //<div id="messages_product_view"><ul class="messages"><li class="error-msg"><ul><li>The requested quantity for "Prod Test 1" is not available. Please enter a smaller quantity.</li></ul></li></ul></div>
            
            var pattern = /<div id="messages_product_view">(.*?)<\/div>/g;
            var result=pattern.exec(data);
            console.log(result)
            if(result) {
                console.log('dasd')
                var msg ='<ul class="messages"><li class="error-msg"><ul><li>The requested quantity for "'+jQuery("#product-description .title").html()+'" is not available. Please enter a smaller quantity.</li></ul></li></ul></div>';
                jQuery("#messages_product_view").html(msg)
                jQuery("#messages_product_view").css("margin-bottom","15px");
                jQuery('.addToCartBtn').removeClass('btnWait');   
                return;
            } else {
                jQuery("#messages_product_view").html('').css("margin-bottom","0px")
            }
            
            var imgPath, pos;
            if(jQuery(".main-image img").length){
                imgPath = jQuery(".main-image img").attr('src')
                pos = jQuery(".main-image img").offset();
                
                imgW = jQuery('.main-image img').attr('width');
                imgH = jQuery('.main-image img').attr('height');
                
            } else if(jQuery('#tag-image-' + product_id).length){
                imgPath = jQuery('#tag-image-' + product_id).attr('src')
                pos = jQuery('#tag-image-' + product_id).offset();
                
                imgW = jQuery('#tag-image-' + product_id).attr('width');
                imgH = jQuery('#tag-image-' + product_id).attr('height');
                
            } else if(jQuery('#whishlist-prod-' + product_id).length){
                
                imgPath = jQuery('#whishlist-prod-' + product_id).attr('src')
                pos = jQuery('#whishlist-prod-' + product_id).offset();
                imgW = jQuery('#whishlist-prod-' + product_id).attr('width');
                imgH = jQuery('#whishlist-prod-' + product_id).attr('height');
                
            }
            

            var destinationPos = jQuery("#minicartBtn").offset();

            //var btnText = jQuery("#minicartBtn").val().replace("MY CART (","").replace(")","");
            //var newVal = "MY CART (" + (parseInt(btnText) + 1) + ")";
            
            updateMiniCart();
            
            jQuery("body").append("<img src='"+imgPath+"' class='fly' style='left:"+pos.left+"px;top:"+pos.top+"px;width:"+imgW+"px;height:"+imgH+"px' />")
            jQuery(".fly").animate({left:destinationPos.left + 70,top:destinationPos.top + 10,width:0,height:0},1000,function(){
                openMiniCart();
                jQuery(".fly").remove();
                /*
                var status = true;
                for(j=0; j < inCart.length; j++) {
                    if(inCart[j] == product_id) {
                        status = false
                    }
                }

                if(status) {
                  //  jQuery("#minicartBtn").val(newVal);
                    inCart[inCart.length] = product_id
                }
                */
                
            })
         
            jQuery('.addToCartBtn').removeClass('btnWait');   
            
              
            //hide loader for wishlist items
            jQuery("#wishlist-btn-cart-" + product_id).parent().find('img').remove();
            jQuery("#wishlist-btn-cart-" + product_id).show();
            
            
        }
    });
}

// add product in mini-cart (fly into cart animation)
function addBundleToCart(prodId, url) {
    //todo add into cart
    
    //check for unselected options
    var ok = true;
    
    var okcount = 0;
    jQuery('select[id^="bundle-option-"]').each(function(i, item){
        
        if(jQuery('a#sbSelector_' + jQuery(item).attr('id')).html() == 'Choose a selection...'){
            ok = false;
            
            if(okcount == 0){
                
                jQuery('#sbHolder_' + jQuery(item).attr('id')).css('border', '2px solid red');
                jQuery('#sbHolder_' + jQuery(item).attr('id') + ' ul li').click(function(){
                    if(jQuery(this).attr('rel') != ''){
                        jQuery('#sbHolder_' + jQuery(item).attr('id')).css('border', '0');
                    }
                });
                window.scrollTo(0, jQuery('#sbHolder_' + jQuery(item).attr('id')).offset().top);
            }
        }
        okcount++;
    });
    
    if(!ok){
        return;
    }
    
    jQuery('.addToCartBundleBtn').addClass('btnWait');
    var r = {};
    jQuery('input[name^="bundle_option"]').each(function(i, item){
        eval('r["' + jQuery(item).attr('name') + '"]=' + jQuery(item).val());
    });
    jQuery('select[name^="bundle_option"]').each(function(i, item){
        eval('r["' + jQuery(item).attr('name') + '"]=' + jQuery(item).val());
    }); 
    
    
    var qty = jQuery("#bqty").val();
    
    r["qty"] = qty;
    var product_id = null;
    
    if(prodId == undefined || prodId == ''){
        product_id = jQuery("#productId").val();
    } else 
        product_id = prodId;

    r["product"] = product_id;

    var optionName = jQuery(".super-attribute-select").attr("name")
    var optionValue = jQuery(".super-attribute-select").val()

    jQuery.ajax({
        //url     : siteUrl + 'checkout/cart/add/product/' + product_id + '/?' + optionName + '=' + optionValue + '&qty=' + qty,
        url: url,
        type    : 'POST',
        //dataType: 'JSON',
        async: true,
        data: r,
        success : function(data) {
            
            var imgPath, pos;
            if(jQuery("#bundle-image img").length){
                imgPath = jQuery("#bundle-image img").attr('src')
                pos = jQuery("#bundle-image img").offset();
            } else if(jQuery('#tag-image-' + product_id).length){
                imgPath = jQuery('#tag-image-' + product_id).attr('src')
                pos = jQuery('#tag-image-' + product_id).offset();
            }

            var destinationPos = jQuery("#minicartBtn").offset();

//            var btnText = jQuery("#minicartBtn").val().replace("MY CART (","").replace(")","");
//            var newVal = "MY CART (" + (parseInt(btnText) + 1) + ")";
            
            updateMiniCart();
            
            jQuery("body").append("<img src='"+imgPath+"' class='fly' style='left:"+pos.left+"px;top:"+pos.top+"px' />")
            jQuery(".fly").animate({left:destinationPos.left + 70,top:destinationPos.top + 10,width:0,height:0},1000,function(){
                openMiniCart();
                jQuery(".fly").remove();
                /*
                var status = true;
                for(j=0; j < inCart.length; j++) {
                    if(inCart[j] == product_id) {
                        status = false;
                    }
                }

                if(status) {
                    jQuery("#minicartBtn").val(newVal);
                    inCart[inCart.length] = product_id;
                }
                
                */
            });
         
            jQuery('.addToCartBundleBtn').removeClass('btnWait')   
            
        }
    })
}

function addBundleToCart1(prodId, url) {
    //todo add into cart
    
    //check for unselected options
    var ok = true;
    
    var okcount = 0;
    jQuery('select[id^="bundle-option-"]').each(function(i, item){
        
        if(jQuery('a#sbSelector_' + jQuery(item).attr('id')).html() == 'Choose a selection...'){
            ok = false;
            
            if(okcount == 0){
                
                jQuery('#sbHolder_' + jQuery(item).attr('id')).css('border', '2px solid red');
                jQuery('#sbHolder_' + jQuery(item).attr('id') + ' ul li').click(function(){
                    if(jQuery(this).attr('rel') != ''){
                        jQuery('#sbHolder_' + jQuery(item).attr('id')).css('border', '0');
                    }
                });
                window.scrollTo(0, jQuery('#sbHolder_' + jQuery(item).attr('id')).offset().top);
            }
        }
        okcount++;
    });
    
    if(!ok){
        return;
    }
    
    jQuery('.addToCartBundleBtn').addClass('btnWait');
    var r = {};
    jQuery('input[name^="bundle_option"]').each(function(i, item){
        eval('r["' + jQuery(item).attr('name') + '"]=' + jQuery(item).val());
    });
    jQuery('select[name^="bundle_option"]').each(function(i, item){
        eval('r["' + jQuery(item).attr('name') + '"]=' + jQuery(item).val());
    }); 
    
    
    var qty = jQuery("#bqty1").val();
    
    r["qty"] = qty;
    var product_id = null;
    
    if(prodId == undefined || prodId == ''){
        product_id = jQuery("#productId").val();
    } else 
        product_id = prodId;

    r["product"] = product_id;

    var optionName = jQuery(".super-attribute-select").attr("name")
    var optionValue = jQuery(".super-attribute-select").val()

    jQuery.ajax({
        //url     : siteUrl + 'checkout/cart/add/product/' + product_id + '/?' + optionName + '=' + optionValue + '&qty=' + qty,
        url: url,
        type    : 'POST',
        //dataType: 'JSON',
        async: true,
        data: r,
        success : function(data) {
            
            var imgPath, pos;
            if(jQuery("#bundle-image img").length){
                imgPath = jQuery("#bundle-image img").attr('src')
                pos = jQuery("#bundle-image img").offset();
            } else if(jQuery('#tag-image-' + product_id).length){
                imgPath = jQuery('#tag-image-' + product_id).attr('src')
                pos = jQuery('#tag-image-' + product_id).offset();
            }

            var destinationPos = jQuery("#minicartBtn").offset();

//            var btnText = jQuery("#minicartBtn").val().replace("MY CART (","").replace(")","");
//            var newVal = "MY CART (" + (parseInt(btnText) + 1) + ")";
            
            updateMiniCart();
            
            jQuery("body").append("<img src='"+imgPath+"' class='fly' style='left:"+pos.left+"px;top:"+pos.top+"px' />")
            jQuery(".fly").animate({left:destinationPos.left + 70,top:destinationPos.top + 10,width:0,height:0},1000,function(){
                openMiniCart();
                jQuery(".fly").remove();
                /*
                var status = true;
                for(j=0; j < inCart.length; j++) {
                    if(inCart[j] == product_id) {
                        status = false;
                    }
                }

                if(status) {
                    jQuery("#minicartBtn").val(newVal);
                    inCart[inCart.length] = product_id;
                }
                
                */
            });
         
            jQuery('.addToCartBundleBtn').removeClass('btnWait')   
            
        }
    })
}

function validatePhysicalGiftCard(){

    resetStatusMsg();
    if (jQuery('#firstname').val()=='') {
            showErrorMsg("Please fill First Name.");
            return false;
    }

    if (jQuery('#lastname').val()=='') {
            showErrorMsg("Please fill Last Name.");
            return false;
    }

    if (jQuery('#address1').val()=='') {
            showErrorMsg("Please fill Address 1.");
            return false;
    }

    if (jQuery('#city').val()=='') {
            showErrorMsg("Please fill City.");
            return false;
    }

    if (jQuery('#s_postcode').val() != '' && ( !isValidPostalCode(jQuery('#s_postcode').val()) && !isValidPostalCode(jQuery('#s_postcode').val(),'CA') )) {
            showErrorMsg("Please use a correct postal code.");
            return false;
    }

    return true;

}

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}


//add product in mini-cart (fly into cart animation)
function addToCartGift(prodId, qty) {
    if(jQuery('#toself_printed').is(':checked') && !validatePhysicalGiftCard()){
        return;
    }

    if (jQuery('#amount').val() == '' || !IsNumeric(jQuery('#amount').val())) {
            resetStatusMsg();
            showErrorMsg("Please enter an amount (must be a number).");
            return;
    }
    
    if ((jQuery('#recipient_email').val() == '' || !validateEmail(jQuery('#recipient_email').val())) && !jQuery('#toself_printed').is(':checked') ) {
            resetStatusMsg();
            showErrorMsg("Please enter an email address.");
            return;
    }

    //var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    //if ( !jQuery('#toself_printed').is(':checked') && ( jQuery('#recipient_email').val()=='' || !emailRegExp.test(jQuery('#recipient_email').val()) )) {
            //resetStatusMsg();
            //showErrorMsg("Please use a correct email address.");
            //return;
    //}

    //todo add into cart
    jQuery('.addToCartBtn').addClass('btnWait');
    if(qty == undefined || qty == ''){
        var qty = jQuery("#qty").val();
    } 
    var product_id = null;
    
    if(prodId == undefined || prodId == ''){
        product_id = jQuery("#productId").val();
    } else 
        product_id = prodId;

    var optionName = jQuery(".super-attribute-select").attr("name")
    var optionValue = jQuery(".super-attribute-select").val()

    var postData = {
        	amount:jQuery("#amount").val(),
        	product:prodId,
        	qty:jQuery("#qty").val()
        }
    postData.recipient_email= jQuery('#recipient_email').val();
    postData.recipient_message= '';
    postData.recipient_address= '';
    postData.recipient_name = '';
    postData.recipient_type= 1;
    
    if(jQuery('#toself_printed').is(':checked')){
    
        var postDataGranular = postData;
    
        postData.recipient_address= jQuery('#address1').val() + ' ' + jQuery('#address2').val() + ' ' + jQuery('#city').val() + ' ' + jQuery('#sbSelector_region_id').html();
        postData.recipient_email= jQuery('#recipient_email').val();
        postData.recipient_message= '';
        postData.recipient_name= jQuery('#firstname').val() + ' ' + jQuery('#lastname').val();
        postData.recipient_type= 1;
        
        postDataGranular.firstname = jQuery('#firstname').val();    
        postDataGranular.lastname = jQuery('#lastname').val();
        postDataGranular.address1 = jQuery('#address1').val();
        postDataGranular.address2 = jQuery('#address2').val();
        postDataGranular.city = jQuery('#city').val();
        postDataGranular.region_id = jQuery('#region_id').val();
        postDataGranular.country = jQuery('#country').val();
        postDataGranular.postcode = jQuery('#s_postcode').val();
        postDataGranular.productId = prodId;
    }

    jQuery.ajax({
        url     : siteUrl + 'checkout/cart/add/product/' + product_id + '/?' + optionName + '=' + optionValue + '&qty=' + qty,
        type    : 'POST',
        data: postData,
        //dataType: 'JSON',
        async: true,
        success : function(data) {
            var imgPath, pos;
            
            if(jQuery("#giftImage img").length){
                imgPath = jQuery("#giftImage img").attr('src')
                pos = jQuery("#giftImage img").offset();
            }
            
            //var btnText = jQuery("#minicartBtn").val().replace("MY CART (","").replace(")","");
            //var newVal = "MY CART (" + (parseInt(btnText) + 1) + ")";
            var destinationPos = jQuery("#minicartBtn").offset();

            updateMiniCart();

            jQuery("body").append("<img src='"+imgPath+"' class='fly' style='left:"+pos.left+"px;top:"+pos.top+"px' />")
            jQuery(".fly").animate({left:destinationPos.left + 70,top:destinationPos.top + 10,width:0,height:0},1000,function(){
                openMiniCart();
                jQuery(".fly").remove();
                /*
                var status = true;
                for(j=0; j < inCart.length; j++) {
                    if(inCart[j] == product_id) {
                        status = false
                    }
                }

                if(status) {
                    jQuery("#minicartBtn").val(newVal)
                    inCart[inCart.length] = product_id
                }
                
                */
            });
            
            if(jQuery('#toself_printed').is(':checked')){
                //add address to registry ajax call
                jQuery.ajax({
                url     : localCodeSiteUrl + 'giftcardaddress/add/',
                type    : 'POST',
                data: postDataGranular,
                //dataType: 'JSON',
                async: true,
                success : function(data) {   
                    jQuery('.addToCartBtn').removeClass('btnWait');
                    jQuery('.msgs').hide();
                    jQuery('#amount').val('')
                    jQuery('.s2 input').val('');
                }});  
            } else {
                jQuery('.addToCartBtn').removeClass('btnWait');
                jQuery('.msgs').hide();
                jQuery('#amount').val('')
                jQuery('#recipient_email').val('')
                
            }
            
        }
    })
}

//ajax update minicart
function updateMiniCart() {
    jQuery('#minicart .cartList .subtitle').after('<div><img src="'+fontSiteUrl+'skin/frontend/default/inpink/images/opc-ajax-loader.gif" /></div>');
    jQuery.ajax({
        url     : siteUrl + 'INPINK/minicart/update/',
        type    : 'POST',
        dataType: 'JSON',
        async: true,
        success : function(data) {
            jQuery("#minicart .cartList").html(data.cartContent);
            jQuery("#minicartBtn").val(data.btnText);
        }
    })
}



function hideClipboard(collectionTooltip) {
    if(collectionTooltip) {
        jQuery("#"+collectionTooltip).fadeOut();
    } else {
        jQuery("#clipboardTooltip").fadeOut();
    }
}

function copyUrlToClipboard(collectionTooltip)
{            
    jQuery(".shareByEmail").hide();
    jQuery(".clipboardTooltip").hide();
    
    //event tracking
    if(jQuery('.detailedBlog').length){
        trackGAEvent('Share', 'Link', 'Blog');
    }
    if(jQuery('#main #shareIcons .clipboardFlash').length){
    	trackGAEvent('Share', 'Link', 'PDP');
    }
    
    if(collectionTooltip) {
        //show results
        jQuery("#"+collectionTooltip).fadeIn();
        setTimeout('hideClipboard("'+collectionTooltip+'")',3000)

    } else {
        //show results
        jQuery("#clipboardTooltip").fadeIn();
        setTimeout('hideClipboard()',3000)
    }
    
}

function closeEmailSharePanel() {
    jQuery(".shareByEmail").fadeOut();
}

function closeAddTagPanel(elem) {
    elem.parents(".addTagPopup").fadeOut();
}

function showEmailSharePanel(containerId) {
    

    if(containerId) {
        jQuery(".shareByEmail").hide();
        jQuery(".shareByEmail input").val('')
        jQuery(".shareByEmail textarea").val('')
        
        jQuery("#"+containerId).fadeIn();
    } else {
        jQuery("#clipboardTooltip").hide();
        jQuery("#shareByEmail input").val('')
        jQuery("#shareByEmail textarea").val('')
        jQuery("#shareByEmail").fadeIn();
    }
    
}

function showAddTagPanel() {
    jQuery(".addTagPopup").fadeIn();    
}


function showEmailMessagesToolTip(elemId,tooltipMsg,container) {
    var elem = jQuery("#" + container + " #"+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("#"+container + " #tooltip_" + elemId + " .body").html(tooltipMsg);
    jQuery("#"+container + " #tooltip_" + elemId).css({left:pos.left,top:pos.top + 25}).fadeIn();
}




function sendEmailToFriends() {
    //validate inputs
    //check if email addresses are valid 
    
    jQuery(".shareByEmail .tooltip").remove();
    var msg = "";
    
    var senderEmail = jQuery("#senderEmailAddress").val();
    var senderName = jQuery("#senderName").val();
    
    var receiverName1 = jQuery("#receiverName_1").val();
    var receiverName2 = jQuery("#receiverName_2").val();
    var receiverName3 = jQuery("#receiverName_3").val();
    
    var receiverEmailAddress1 = jQuery("#receiverEmailAddress_1").val();
    var receiverEmailAddress2 = jQuery("#receiverEmailAddress_2").val();
    var receiverEmailAddress3 = jQuery("#receiverEmailAddress_3").val();
    
    var message = jQuery("#message").val();
    var productUrl = location.href;
    var description = jQuery("#product_description").val();
    var thumbnail = jQuery("#product_thumbnail").val();
    
    var receivers = new Array();
    jQuery(".receiver .textinput").each(function(){
        if(jQuery(this).val()!='') {
            receivers.push(jQuery(this).attr("id"))
        }
    })   
    
    
    if(trimAll(senderName) == "") {
        msg = "Sender Name is required";  
        showEmailMessagesToolTip("senderName",msg,"shareByEmail");
        jQuery("#senderName").addClass("invalidInput");
        
    } else if(trimAll(senderEmail) == "") {
        
        msg = "Email address is required";
        showEmailMessagesToolTip("senderEmailAddress",msg,"shareByEmail");
        
    } else if(!validateEmail(senderEmail)) {
        
        msg = "Please make sure your email address is correct.";
        showEmailMessagesToolTip("senderEmailAddress",msg,"shareByEmail");
        
    } else if(receivers.length == 0)  {
        msg = "Please add at least one receiver!";
        showEmailMessagesToolTip("receiverName_1",msg,"shareByEmail");
        
    } else {
       
        for(i=0;i < receivers.length;i++) {
            var emailRow = receivers[i]
            var rowParts = emailRow.split('_');
            
            if(rowParts[0] == 'receiverName') {
                
                var emailVal = trimAll(jQuery("#receiverEmailAddress_" + rowParts[1]).val()); 
                
                if(emailVal == "") {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverEmailAddress_" + rowParts[1],'Email address is required!',"shareByEmail");
                    jQuery("#receiverEmailAddress_"+rowParts[1]).addClass("invalidInput");
                } else if(!validateEmail(jQuery("#receiverEmailAddress_" + rowParts[1]).val())) {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverEmailAddress_" + rowParts[1],'Email address is invalid!',"shareByEmail");
                    jQuery("#receiverEmailAddress_"+rowParts[1]).addClass("invalidInput");
                }
                
            } else if(rowParts[0] == 'receiverEmailAddress') {
                
                var nameVal = trimAll(jQuery("#receiverName_" + rowParts[1]).val()); 
                
                if(nameVal == "") {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverName_" + rowParts[1],'Name is required!',"shareByEmail");
                    jQuery("#receiverName_"+rowParts[1]).addClass("invalidInput");
                    
                } else if (!validateEmail(jQuery("#receiverEmailAddress_" + rowParts[1]).val())) {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverEmailAddress_" + rowParts[1],'Email address is invalid!',"shareByEmail");
                    jQuery("#receiverName_"+rowParts[1]).addClass("invalidInput");
                    
                } 
                
            } else {
                msg = '';
            }
        }

        if(msg == '') {
             jQuery.ajax({
                url     : siteUrl + 'INPINK/sendfriend/send/',
                type    : 'POST',
                data    : {'senderName':senderName,'senderEmail':senderEmail,'receiversName':receiverName1+"|"+receiverName2+"|"+receiverName3,'receiversEmail':receiverEmailAddress1+"|"+receiverEmailAddress2+"|"+receiverEmailAddress3,'message':message,'productUrl':productUrl, description: description, thumbnail: thumbnail},
                dataType: 'JSON',
                async: true,
                success : function(data) {
                   // console.log(data)
                   //var response = eval('('+data+')');
                   var response = data;
                   if(response.status=='OK') {
                        jQuery(".shareByEmail input").val('');
                        jQuery(".shareByEmail textarea").val('');
                        showSuccessMessage()
                    }
                    
                    closeEmailSharePanel();
                }
            })
        }
    }    
}

function showSuccessMessage(container) {
    if(container) {
        var p = container.split("_")

        jQuery("#shareIcons_"+p[1]+" .emailShareMessageTooltip").fadeIn();
        setTimeout('hideSuccessMessage("emailShareMessageTooltip")',4000)
    } else {
        jQuery(".emailShareMessageTooltip").fadeIn();
        setTimeout('hideSuccessMessage("emailShareMessageTooltip")',4000)
    }
    
}
function hideSuccessMessage(elementId) {
    jQuery('.'+elementId).fadeOut();
}


function checkPressedKey(evt)
{    
    if (evt.keyCode == 13)
        submitNewsletterSubscription();
}


function sendCollectionEmailToFriends(collectionContainerId) {
    //validate inputs
    //check if email addresses are valid

    jQuery(".shareByEmail .tooltip").remove();
    var msg = "";

    var senderEmail = jQuery("#"+collectionContainerId+" #senderEmailAddress").val();
    var senderName = jQuery("#"+collectionContainerId+" #senderName").val();

    var receiverName1 = jQuery("#"+collectionContainerId+" #receiverName_1").val();
    var receiverName2 = jQuery("#"+collectionContainerId+" #receiverName_2").val();
    var receiverName3 = jQuery("#"+collectionContainerId+" #receiverName_3").val();

    var receiverEmailAddress1 = jQuery("#"+collectionContainerId+" #receiverEmailAddress_1").val();
    var receiverEmailAddress2 = jQuery("#"+collectionContainerId+" #receiverEmailAddress_2").val();
    var receiverEmailAddress3 = jQuery("#"+collectionContainerId+" #receiverEmailAddress_3").val();

    var message = jQuery("#"+collectionContainerId+" #message").val();
    var productUrl = location.href;

    if(jQuery("#"+collectionContainerId+"_productUrl").val()) {
       productUrl = jQuery("#"+collectionContainerId+"_productUrl").val();
    }
    
    var receivers = new Array();
    jQuery("#"+collectionContainerId+" .receiver .textinput").each(function(){
        if(jQuery(this).val()!='') {
            receivers.push(jQuery(this).attr("id"))
        }
    })
    
    if(trimAll(senderName) == "") {
        msg = "Sender Name is required";
        showEmailMessagesToolTip("senderName",msg,collectionContainerId);
        jQuery("#"+collectionContainerId+" #senderName").addClass("invalidInput");

    } else if(trimAll(senderEmail) == "") {

        msg = "Email address is required";
        showEmailMessagesToolTip("senderEmailAddress",msg,collectionContainerId);

    } else if(!validateEmail(senderEmail)) {

        msg = "Please make sure your email address is correct.";
        showEmailMessagesToolTip("senderEmailAddress",msg,collectionContainerId);

    } else if(receivers.length == 0)  {
        msg = "Please add at least one receiver!";
        showEmailMessagesToolTip("receiverName_1",msg,collectionContainerId);

    } else {

        for(i=0;i < receivers.length;i++) {
            var emailRow = receivers[i]
            var rowParts = emailRow.split('_');

            if(rowParts[0] == 'receiverName') {

                var emailVal = trimAll(jQuery("#"+collectionContainerId+" #receiverEmailAddress_" + rowParts[1]).val());

                if(emailVal == "") {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverEmailAddress_" + rowParts[1],'Email address is required!',collectionContainerId);
                    jQuery("#" + collectionContainerId+" #receiverEmailAddress_"+rowParts[1]).addClass("invalidInput");
                } else if(!validateEmail(jQuery("#" + collectionContainerId+" #receiverEmailAddress_" + rowParts[1]).val())) {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverEmailAddress_" + rowParts[1],'Email address is invalid22!',collectionContainerId);
                    jQuery("#" + collectionContainerId+" #receiverEmailAddress_"+rowParts[1]).addClass("invalidInput");
                }

            } else if(rowParts[0] == 'receiverEmailAddress') {

                var nameVal = trimAll(jQuery("#" + collectionContainerId+" #receiverName_" + rowParts[1]).val());

                if(nameVal == "") {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverName_" + rowParts[1],'Name is required!',collectionContainerId);
                    jQuery("#" + collectionContainerId+" #receiverName_"+rowParts[1]).addClass("invalidInput");

                } else if (!validateEmail(jQuery("#" + collectionContainerId+" #receiverEmailAddress_" + rowParts[1]).val())) {
                    msg='notOK'
                    showEmailMessagesToolTip("receiverEmailAddress_" + rowParts[1],'Email address is invalidqq!',collectionContainerId);
                    jQuery("#" + collectionContainerId+" #receiverName_"+rowParts[1]).addClass("invalidInput");

                }

            } else {
                msg = '';
            }
        }

        if(msg == '') {
             jQuery.ajax({
                url     : siteUrl + 'INPINK/sendfriend/send/',
                type    : 'POST',
                data    : {'senderName':senderName,'senderEmail':senderEmail,'receiversName':receiverName1+"|"+receiverName2+"|"+receiverName3,'receiversEmail':receiverEmailAddress1+"|"+receiverEmailAddress2+"|"+receiverEmailAddress3,'message':message,'productUrl':productUrl},
                dataType: 'JSON',
                async: true,
                success : function(data) {
                    //var response = eval('('+data+')');
                    var response = data;
                    if(response.status=='OK') {
                        jQuery(".shareByEmail input").val('');
                        jQuery(".shareByEmail textarea").val('');
                    }
                    closeEmailSharePanel();
                    showSuccessMessage(collectionContainerId)
                }
            })
        }
    }
}


