"use strict";
$(function() {
	
    REGISTER.init();
    $(document).on('change','.type_payment',function(){
        var selft = $(this); 
        var methodPay =   selft.val();
        if (methodPay === 'bank') {
            $('.pttt_pay').addClass('ptttactive');
        }else {
            $('.pttt_pay').removeClass('ptttactive');
        }
    })
/*
    $("#boxscroll").niceScroll({cursorborder:"",cursorcolor:"#8198a6",boxzoom:false});
    $(window).bind('scroll', function() {
        200 <= $(this).scrollTop() ? $("#to_top").fadeIn() : $("#to_top").fadeOut();
		
		if($(this).scrollTop()==0 ){ 
			$("#topHeader").removeClass('fix'); 
		}else{$("#topHeader").addClass('fix');
		} 
    });*/
	
	   $('.product-rows .boxes-color').click(function(){
			$('.product-rows .boxes-color').removeClass('choicactive');
           var color = $(this).attr('relcolor'); 
            $(this).addClass('choicactive');
            $('#codeColor').val(color);
           

        });
		 $('.product-rows .boxes-size').click(function(){
			$('.product-rows .boxes-size').removeClass('choicactive');
            var color = $(this).attr('relsize');
            $(this).addClass('choicactive');
            $('#codeSize').val(color);
            return false;

        });

});

var REGISTER = {
    OBJ_GRID: null,
    init: function() {
       var  data = '';
        
        $('form.addtoCart').submit(function(e){

            e.preventDefault();
            REGISTER.addtoCart();
            return false;
        });
        
        $(document).on("click", ".payment-accept", function(e) {
            e.preventDefault();
             $(this).hide();
            var flag=true;
            // ,form#inforOrderCart :input[type="email"]
            $('form#inforOrderCart :input[type="text"],form#inforOrderCart :input[type="tel"], .type_payment').each(function() {
                if($(this).val()==''){
                    $(this).css('border','1px solid #ff0000');
                    flag=false;
                }else{ $(this).css('border','1px solid #ccc');
                    /*if(isNaN($(this).val())==true || ($(this).val().length>2)){
                        $(this).css('border','1px solid #ff0000');
                        flag=false;

                    }else{  }*/
                }

            });
            if(flag==true){
                REGISTER.saveOrder();
            }else{
                $('#message.alert-danger').text('Vui lòng nhập đầy đủ thông tin người mua hàng ở trên').show();
                $(this).show();
            }

            return false;
        });

        $(document).on('click','#fill_product .checkbox',function(){
            var linkFill = $('#idfillter').attr('data-link');
            var ifrice = ($(this).find('.typepr').val());
            location.href= linkFill+'?featured='+ifrice;
            return false;

        });
        $(document).on('click','#fillter_price .checkbox',function(){
           var linkFill = $('#idfillter').attr('data-link');
            var ifrice = ($(this).find('.ifrice').val());
            location.href= linkFill+'?price='+ifrice;
            return false;

        });
        $(document).on('click','#orderCart',function(){
            REGISTER.orderCart();
            return false;

        });
		
		
        $(document).on('click','.size-table',function(){
            $('#table-size').modal('show');
            return false;

        });
		
		
        $(document).on('click','#itemviewvideo',function(){
            var link    = $(this).attr('reldata');
            var title   = $(this).attr('reltitle');
            link = link.split('/');
            var code= link[(link.length)-1];
            $('#maintainvideo').html('<iframe width="100%" height="480" src="https://www.youtube.com/embed/'+code+'" frameborder="0" allowfullscreen></iframe>');
            $('#titlevideo').html(title);
            $('#popupvideo').modal('show');
            return false;

        });
        $('#popupvideo').on('hidden.bs.modal', function (e) {
            $('#maintainvideo').html('');
        })
        
     
        /*$(document).on('click','.product-rows .boxes-size',function(){
			$('.product-rows .boxes-size').removeClass('choicactive');
            var color = $(this).attr('relsize');
            $(this).addClass('choicactive');
            $('#codeSize').val(color);
            return false;

        });*/
        $(document).on('click','.delete',function(){
            var idclick = $(this).attr('relid');
            $('#itemcart_'+idclick+'').remove();
            $.ajax({
                url: url_site+'fajax/deleteCart',
                type: 'POST',
                dataType: 'JSON',
                data: {'rowid':idclick},
                beforeSend: REGISTER.startLoading,
                complete: REGISTER.topLoading
            }).done(function(response) {
                if(response.count>0){
                    $('.numcart').text(response.count);
                }else{
                 location.href=url_site;   
                }
                //$('#itemcart_'+idclick+' .subtotal').text(response.price);
            });
        });
        $(document).on('click','.decrease',function(){
            var idclick = $(this).attr('relid');
            var qty =  $('.itemcart_'+idclick).val();
            
            var qincrea = (parseInt(qty))
            if(qincrea>1 && qincrea<=10){
                
                $('.itemcart_'+idclick).val((qincrea)); 
            }else{
                qincrea =1;
                $('.itemcart_'+idclick).val(qincrea);  
            }

            $.ajax({
                url: url_site+'fajax/updateCart',
                type: 'POST',
                dataType: 'JSON',
                data: {'qty':qincrea,'rowid':idclick},
                beforeSend: REGISTER.startLoading,
                complete: REGISTER.topLoading
            }).done(function(response) {
                $('#itemcart_'+idclick+' .subtotal').text(response.price);
            });
            
            return false;

        });
        
        $(document).on('click','.increase',function(){
            var idclick = $(this).attr('relid');
            var qty =  $('.itemcart_'+idclick).val();
           var qincrea=10;
            if(qty<10){
                var qincrea = (parseInt(qty))
                $('.itemcart_'+idclick).val((qincrea));
            }else{
                $('.itemcart_'+idclick).val(qincrea);
            }
            $.ajax({
                url: url_site+'fajax/updateCart',
                type: 'POST',
                dataType: 'JSON',
                data: {'qty':qincrea,'rowid':idclick},
                beforeSend: REGISTER.startLoading,
                complete: REGISTER.topLoading
            }).done(function(response) {
               $('#itemcart_'+idclick+' .subtotal').text(response.price); 
            });
            
            return false;

        });  
        $(document).on("submit", "form.question", function(e) {
            e.preventDefault();
            REGISTER.Savecomment();
            return false;
        });

        $(document).on("submit", ".contact-form", function(e) {
           // e.preventDefault();
            var data = $('form.contact-form').serializeArray(); 
            var flag=true;
            $.each(data, function(i, field) {
                if($('input[name='+field.name+']').val()==''){
                    $('input[name='+field.name+']').css('border', '1px solid #ff0000');
                    flag =false; 
                }else{
                    $('input[name='+field.name+']').css('border', '1px solid #ccc');  
                }
                if($('textarea[name='+field.name+']').val()==''){
                    $('textarea[name='+field.name+']').css('border', '1px solid #ff0000');
                    flag =false;
                }else{
                    $('textarea[name='+field.name+']').css('border', '1px solid #ccc');
                }
                
               
                //var input = $('input[name='+field.name+']');
               // field.value = $.trim(field.value);
               // switch(field.name){
                   
               // }
           }) ; 
           //alert( flag);   
            return flag;
        });

    },
    startLoading: function() {
        $('#loading').html('<img src="'+url_site+'static/images/loading.gif" />');
        $('#loading').show();
        $('#loading').css({display: 'inline'});
    },
    topLoading: function() {
        $('#loading').hide();
        $('#loading').html('');

    },
/*============================== SendFranchise ===================*/
    addtoCart:function(){
        var f='.addtoCart ';
        var formData = $('form.addtoCart').serializeArray();

        $('#message').html('');
       // if(full_name && email && phone_number && place_frenchise && optionrow_myself && rtotp){
            $.ajax({
                url: url_site+'fajax/addtoCart',
                type: 'POST',
                dataType: 'JSON',
                data: formData,
                beforeSend: REGISTER.startLoading,
                complete: REGISTER.topLoading
            }).done(function(response) {
                console.log(response);
                if (response.code == 0) {
                    $('.totalitem').text(response.totalOrder);
                     REGISTER.showSuccess ('<li> '+response.message+'</li>');
                    //$(f +'input[type="text"],'+f +'input[type="number"],'+f +'input[type="email"],'+f +'textarea').val('');
                    setInterval(function(){
                    location.href=url_site+'dat-hang.html';
                }, 2000);
                } else {
                     REGISTER.showError ('<li> '+response.message+'</li>');

                     //$('#message.alert-danger').text(response.message).show();
                }
            });
       // }else{
          //  $('#message.alert-danger').text('Vui lòng nhập đầy đủ thông tin').show();
        //}
    },
    saveOrder:function(){
        var formData = $('form#inforOrderCart').serializeArray();
        var f='#inforOrderCart ';
        $('#message').html('');
        $('#message').hide();
        // if(full_name && email && phone_number && place_frenchise && optionrow_myself && rtotp){
        $.ajax({
            url: url_site+'fajax/saveOrder',
            type: 'POST',
            dataType: 'JSON',
            data: formData,
            beforeSend: REGISTER.startLoading,
            complete: REGISTER.topLoading
        }).done(function(response) {
           
            if (response.code == 0) { 
                $(f +'input[type="text"],'+f +'input[type="number"],'+f +'input[type="email"],'+f +'textarea').val('');
                ///$('#message.alert-success').text(response.message).show();
                 REGISTER.showSuccess ('<li> '+response.message+'</li>');
                setInterval(function(){
                    location.href=response.url_site;
                }, 2000);
            
            } else {
                $(this).show();
                REGISTER.showError ('<li> '+response.message+'</li>');
            }
        });
        // }else{
        //  $('#message.alert-danger').text('Vui lòng nhập đầy đủ thông tin').show();
        //}
    },
    orderCart:function(){
        $.ajax({
            url: url_site+'fajax/orderCart',
            type: 'POST',
            dataType: 'JSON',
            data: '',
            beforeSend: REGISTER.startLoading,
            complete: REGISTER.topLoading
        }).done(function(response) {
            console.log(response);
            if (response.code == 0) {
                $('.order_cart').html(response.data);
            } else {
                $('#message.alert-danger').text(response.message).show();
            }
        });
    },
    Savecomment:function(){
        var f ='.question ';
        var fullname = $(f+'#fullname').val();
        var email = $(f+'#email').val();
        var condition   = $(f+'#fcontent').val();
       
        var token = $(f+'#token').val();
      

        if(fullname && email && condition && token){
            $.ajax({
                url: url_site+'fajax/savefeedback',
                type: 'POST',
                dataType: 'JSON',
                data: {'fullname':fullname,'email':email, 'condition': condition,'token':token},
                beforeSend: REGISTER.startLoading,
                complete: REGISTER.topLoading
            }).done(function(response) {
                $(f+'#message').hide();
                if (response.code == 0) {
                    $(f+'#message.alert-success').text(response.message).show();
                } else {
                    $(f+'#message.alert-danger').text(response.message).show();
                }
            });
        }else{
            $('#message.alert-danger').text('Vui lòng nhập đầy đủ thông tin').show();
        }
    },
    showSuccess:function (obj) {
        $('#showmsg ul').html('');
        $('#showmsg ul').addClass('listesuccess');
        $('#showmsg ul').html(obj);
        $('#showmsg').fadeIn(1200).delay(1000).fadeOut(2000,function(){
            $("#showmsg ul").removeClass ("listesuccess");
        })
    },
     showError:function (obj) {
        $('#showmsg').hide();
        $('#showmsg ul').html('');
        $('#showmsg ul').addClass('listerror');
        $('#showmsg ul').html(obj);
        // $.each(obj, function( index, value ) {
        //
        // });
        //$("#showmsg").fadeOut(1200, function() {
            $('#showmsg').fadeIn(500).delay(1000).fadeOut(2000,function(){
               // $("#bookingcar").removeAttr("disabled");
                $("#showmsg ul").removeClass ("listerror");
            })
        //});
        // $(' #msg.'+valclass).fadeIn(2000).next().delay(5000).fadeOut();
    }

}