Subversion Repositories SmartDukaan

Rev

Rev 14432 | Rev 14579 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

var livePriceCalls = [];
var outOfStockCount = 0;
$(function(){   
        if($('.scroll > .card').length>0) {
                setTimeout(function(){ document.location.reload(); }, 1000*60*35);
                $('.scroll').jscroll({
                        loadingHtml: '<center><img src="/img/ajax-loader.gif" alt="Loading" /></center>',
                    autoTriggerUntil: 3,
                    padding: 20,
                });
        }
        if($('.storeminprice').length>0) {
                var globalminprice = 9999999;
                var globalminsku;               
                var calls = [];
                $('.storeminprice').each(function(){
                        var temp = {'sort':$(this).data('searchorder'),'val':$(this)};
                        calls.push(temp);
                });
                calls = sortByKey(calls,'sort');                
                for(var i in calls){
                        fetchLivePrice(calls[i]['val'])
                }               
        };
        function sortByKey(array, key) {
            return array.sort(function(a, b) {
                var x = a[key]; var y = b[key];
                return ((x < y) ? -1 : ((x > y) ? 1 : 0));
            });
        };
        function fetchLivePrice(obj){           
                var that = obj; 
                var inStock = false;            
                var req = $.ajax({
                        url: '/store_products/getliveprice/'+$(that).data('bundle_id')+'/'+$(that).data('id'),
                        // Tell jQuery we're expecting JSONP
                        dataType: "json",
                        // Tell YQL what we want and that we want JSON                  
                        method: 'get',
                        // timeout: 30000,
                        // Work with the response
                        success: function( response ) {
                                if(response.success){
                                        var i = 0;      
                                        var minpriceindex = 0;                          
                                        if(response.products[i].in_stock == 1){inStock = true;}
                                        var minprice = response.products[0]['available_price'];
                                        var minpriceurl = response.products[0]['marketPlaceUrl'];
                                        if(response.products.length>0){
                                                //More than one products in store
                                                var variants = [];
                                                // var i = 0;
                                                for(var i in response.products){        
                                                        if(response.products[i].in_stock == 1){inStock = true;}                                         
                                                        // console.log(response.products[i]);
                                                        if(response.products[i].available_price && response.products[i].available_price < globalminprice) {
                                                                globalminprice = Math.round(response.products[i].available_price);
                                                                globalminsku = response.products[i]._id;
                                                        }
                                                        if(response.products[i].available_price <= minprice) {
                                                                minprice = Math.round(response.products[i].available_price);
                                                                minpriceindex = i;
                                                        } 
                                                        variants.push({'available_price' : Math.round(response.products[i].available_price), 'url' : response.products[i].marketPlaceUrl,'source_product_name' : response.products[i].source_product_name,'id' : response.products[i]._id});
                                                }
                                                if(i>0){
                                                        var variantslink = $('<span class="variants">+ '+i+' Options</span>');
                                                        $(that).parent().append(variantslink);                                                  
                                                        $(variantslink).data('variants',variants)
                                                }
                                        }
                                        if(inStock){
                                                $(that).html(minprice);
                                                $('#sku-'+$(that).data('id')).data('id',response.products[minpriceindex]['_id']).removeClass('hidden');
                                                // console.log(globalminprice+' '+globalminsku);
                                                if(globalminprice != 9999999) {
                                                        $('#bestprice').html(globalminprice);
                                                        $('#beststorelink').data('id',globalminsku).removeClass('hidden');
                                                        $('#bestpricecontainer').removeClass('hidden');
                                                } 
                                        } else{
                                                outOfStockCount++;
                                                $(that).parent().parent().remove();     
                                        }
                                        if(!response.products[0].available_price){
                                                // outOfStockCount++;
                                                // $(that).parent().parent().remove();  
                                                var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
                                                $(that).html(btn);
                                        }
                                } else{
                                        // outOfStockCount++;
                                        // $(that).parent().parent().remove();
                                        var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
                                        $(that).html(btn);
                                }
                                checkForOutStocks(outOfStockCount);
                        },
                        error: function(request, status, err) {
                                //console.log(status+' '+err+' '+request);
                // if (status == "timeout") {
                        var btn = $("<a class='tryagainforliveprice btn btn-xs btn-warning' title='Try Again'>Try Again</a>");
                                        $(that).html(btn);
                                // } else {
                                        // $(that).parent().parent().remove();
                                // }
                        }
                });
                livePriceCalls.push(req);
        };
        function checkForOutStocks(count){
                if(count>=livePriceCalls.length){
                        $('#bestpricecontainer').html('<h4>Out of stock</h4>').removeClass('hidden');   
                }
        };
        $(document).on('click','.variants',function(){
                $('.storeproductinfo').empty();
                var variants = $(this).data('variants');        
                $('#variantscount').html(variants.length);
                for(var i in variants){
                        // console.log(variants[i]);
                        var row = $('<div class="row storeproductinfo"><div class="col-xs-7">'+variants[i].source_product_name+'</div><div class="col-xs-3">'+variants[i].available_price+'</div><div class="col-xs-2"><button class="btn btn-primary btn-xs viewproduct" type="button" data-id="'+variants[i].id+'">Buy</button></div></div>');
                        $('#storeproducts').parent().append(row);
                }
                // console.log($(this).parent());
                $('#storename').html($(this).parent().data('storename'));
                $('#variantModal').modal();
        });
        $('.categorytab').on('click','.categorytabcontrol.active',function(){
                $(this).toggleClass('active');
                $('#preferences-'+$(this).data('id')).addClass('hidden');
                $(this).parent().parent().children().find('.savecategorypreferences',0).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
        });
        $('.categorytab').on('click','.categorytabcontrol:not(.active)',function(){
                $(this).parent().parent().find('.btn',0).click();
        });
        $('.categorytab').on('click','.editcategorypreferences',function(e){
                var that = $(this);
                $(that).removeClass('editcategorypreferences').addClass('savecategorypreferences').html('Done').addClass('btn-success');
                $('#togglepreferences-'+$(that).data('id')).toggleClass('active');
                $('#preferences-'+$(that).data('id')).removeClass('hidden');
                $('.brandselector').each(function(){
                        if($(this).data('catid')==$(that).data('id')){
                                $(this).addClass('active');
                        }
                });
        });
        $('.categorytab').on('click','.savecategorypreferences',function(e){
                var that = $(this);
                $(that).removeClass('savecategorypreferences').addClass('editcategorypreferences').html('Edit').removeClass('btn-success');
                $('#togglepreferences-'+$(that).data('id')).toggleClass('active');
                $.ajax({
                        url: $('#categorypreference-'+$(that).data('id')).attr('action'),
                        data: $('#categorypreference-'+$(that).data('id')).serialize(),
                        // Tell jQuery we're expecting JSONP
                        dataType: "json",
                        // Tell YQL what we want and that we want JSON                  
                        method: 'post',
                        // Work with the response
                        success: function( response ) {
                                if(response.success){
                                        $('#preferences-'+$(that).data('id')).addClass('hidden');
                                }
                        }
                });
                ga('send', 'event', 'preferences', 'update', me);
        });
        // $('.row').on('click','.viewproduct',function(e){
        $(document).on('click','.viewproduct',function(e){
                if(typeof livePriceCalls != undefined) {
                for(var i in livePriceCalls){
                        // console.log('killing ajax call '+i);
                        livePriceCalls[i].abort();
                }
            }
                $('#loadingModal').modal();
                // console.log($(this).data('id'));
                var url = apihost+"clicks/add/"+me+"/"+$(this).data('id')+'/'+$(this).data('source')+'/?url='+encodeURIComponent($(this).data('url'))+'&price='+$(this).data('price');
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                if(response.success && response.type=='redirect'){
                                        document.location = response.url;
                                }
                        }
                });
                ga('send', 'event', 'product', 'click', $(this).data('url'));
        });
        $('.jscroll-inner').on('click','.likedeal',function(e){ 
                var that = $(this);
                if($(that).hasClass('active')){
                        //User has already liked it,so remove like
                        var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/like";       
                }else{
                        var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/like";
                }
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                if(response.success){
                                        $(that).toggleClass('active');
                                        $(that).parent().find('li.dislikedeal',0).removeClass('active');
                                }
                        }
                });
                ga('send', 'event', 'product', 'like', $(this).data('id'));
        });
        $('#myModal').on('click','#unlikebtn',function(e){
                e.preventDefault();
                var url = $('#unlikeproductform').attr('action')+'?'+$('#unlikeproductform').serialize()
                // console.log(url);
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                // console.log(response);                                               
                        }
                });
                $('#myModal').modal('hide');
                ga('send', 'event', 'brand', 'hide', $('#myModal').find('#productToHide',0).val());
        })
        $('.jscroll-inner').on('click','.dislikedeal',function(e){                      
                var that = $(this);
                if($(that).hasClass('active')){
                        //User has already liked it,so remove like
                        var url = apihost+"/user_actions/rem/"+me+"/"+$(this).data('id')+"/dislike";    
                }else{
                        // console.log('show modal');
                        $('#myModal').find('#productToHide',0).val($(this).data('id'));
                        //$('#myModal').modal();
                        var url = apihost+"/user_actions/update/"+me+"/"+$(this).data('id')+"/dislike";
                }
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                if(response.success){
                                        $(that).toggleClass('active');
                                        $(that).parent().find('li.likedeal',0).removeClass('active');
                                }
                        }
                });
                ga('send', 'event', 'product', 'dislike', $(this).data('id'));
        });
        $('.deletefav').on('click',function(){
                var that = $(this);
                $('#loadingModal').modal();
                var url = apihost+"/user_actions/deletefav/"+me+"/"+$(this).data('id');                 
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                $('#loadingModal').modal('hide');
                                if(response.success){                   
                                        $('#fav-'+$(that).data('id')).hide('slow');
                                }
                        }
                });
                ga('send', 'event', 'favourites', 'remove', $(this).data('id'));
        });
        $('.clearfavs').on('click',function(){
                var that = $(this);
                $('#loadingModal').modal();
                var url = apihost+"/user_actions/deleteallfavs/"+me+'/'+$(this).data('type');                   
                $.ajax({
                        url: url,
                        // The name of the callback parameter, as specified by the YQL service
                        jsonp: "callback",
                        // Tell jQuery we're expecting JSONP
                        dataType: "jsonp",
                        // Tell YQL what we want and that we want JSON
                        data: {
                                format: "json"
                        },
                        // Work with the response
                        success: function( response ) {
                                $('#loadingModal').modal('hide');
                                if(response.success){                   
                                        $('.deletefav').each(function(){
                                                $('#fav-'+$(this).data('id')).hide('slow');
                                        })                                      
                                }
                                $(that).hide();
                        }
                });
                ga('send', 'event', 'favourites', 'removeall', me);
        });
        $('.revealbrands').on('click',function(){
                $(this).parent().find('.notfeatured').toggleClass('hidden');
                if($(this).html()=='Others'){
                        $(this).html('Hide');
                }else{
                        $(this).html('Others');
                }
        });
        $(document).on('click','.creditedcashbacks',function(){
                if($(this).find('.glyphicon-plus',0).length>0){
                        $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
                }else{
                        $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
                }
                $(this).next().toggleClass('hidden');
        });
        $(document).on('click','.panel-heading',function(){
                if($(this).find('.glyphicon-plus',0).length>0){
                        $(this).find('.glyphicon-plus',0).removeClass('glyphicon-plus').addClass('glyphicon-minus');
                }else{
                        $(this).find('.glyphicon-minus',0).removeClass('glyphicon-minus').addClass('glyphicon-plus');
                }
        });
        $(document).on('click','.prefcatselect',function(){
                $('.prefcatselect').removeClass('active')
                $(this).addClass('active');
                $('.categorypreferences').addClass('hidden');
                $('#cat-'+$(this).data('id')).toggleClass('hidden');
        });
        $(document).on('click','.refresh',function(){
                document.location.reload();
        });
        $(document).on('click','.hasmoretext',function(){
                $('#fulltext').html($(this).data('fulltext'));
                $('#fullTextModal').modal();
        });
        $(document).on('click','.favswitch',function(){
                $('.favswitch').removeClass('active')
                $(this).addClass('active');
                $('.clearfavs').addClass('hidden');
                $('.card').addClass('hidden');
                $('.'+$(this).data('type')).removeClass('hidden');
        });
        $(document).on('click','.brandpreferences .brands',function(){
                $(this).parents('.row').siblings('.controls').find('.editcategorypreferences',0).click();
        });
        $(document).on('click','.tryagainforliveprice',function(){              
                fetchLivePrice($(this).parent());
                $(this).parent().html('Getting Live Prices');
        });
});