﻿azd = {
    
    domain    : '',
    extension : '',
    id        : 0 ,
    i	      : 0 ,
    name      : '',
    lenD      : 0,
    domains   : Array(),
    dCart     : Array(),
    dInter    : Array(),
    count     : 0,
    lc        : 0,
    frm       : false,
    first     : 0,
    webroot   : '',
    bool      : true,
    init:function(webroot){
        
            azd.webroot = webroot;
            azd.checkbox();
            azd.count = 0;
            
            azd.checkCart();
            /* navigation menu */
             $("#navbar ul > li").hover(function() {
                  $(this).find('a:first').addClass('active');
                  $(this).find(".navbox").stop(true, true).slideDown('slow','easeOutBounce','easeInOutCirc');
                  $(this).find('img').hide().stop(true, true).slideDown('slow','easeOutBounce','easeInOutCirc');
                }, function() {
                  $(this).find('a:first').removeClass('active');
                  $(this).find(".navbox").stop(true, true).slideUp('fast','easeOutBounce','easeInOutCirc');
             });
             //$('.hover').hide();
             $('#works li').live('mouseenter', function() { // mousein
                    $(this).find('.hover').stop().fadeTo(400,1);
             }).live('mouseleave', function() { // mouseout
                    $(this).find('.hover').stop().fadeTo(400,0);
             });
             
             
             
             
             $('input:text[name="data[domaine][name]"]').val('');
             /* keyup domaine name  */
             $('input:text[name="data[domaine][name]"]').keyup(function(){
                azd.checkbox();
                if($(this).val() == ''){
                    $('#domaineCheckForm').find('.error').text('عذرا اسم النطاق فارغ');
                    azd.frm = false;
                }else if(!$(this).val().match(/^[A-Za-z0-9\-]+$/i)){
                    $('#domaineCheckForm').find('.error').text('عذرا لم تدخل اسم نطاق صالح');
                    azd.frm = false;
                }else{
                    $('#domaineCheckForm').find('.error').text(' ');
                    azd.name = $(this).val();
                    azd.frm  = true;
                }
            });
            
            $('input:checkbox[name="data[domaine][extension][]"]').click(function(){
                if($(this).attr('checked') != undefined){
                    azd.extension = $(this).next().text();
                    azd.id        = $(this).val();
                    azd.first     = 'first';
                    // if ! frm is valid 
                    if(!azd.frm){
                        $('input:text[name="data[domaine][name]"]').trigger('keyup');
                        return false;
                    }
                    else 
                    {  
                        $(this).attr('disabled','');
                        azd.domain  = azd.name + azd.extension;
                        azd.i          = true;
                        azd.domains[0] = azd.domain;
                        azd.check();
                        azd.si();
                        azd.domainF();
                    }
                }
            });
            
            
            // length of domains !!!
            azd.lenD  = 0;
            $('input:checkbox[name="data[domaine][extension][]"]').each(function(){
                azd.lenD++;
            });
            
            
             $('#UserLoginForm').submit(function(){
                        valid = true;
                        msg   = '';              
                        id    = $('#UserUsername').val();
                        pass  = $('#UserPassword').val();
                        if(id == ''){
                            $('#UserLoginForm').find('.error:first').text('لم تقم بإدخال اسم المستخدم').hide().fadeIn('slow');
                            $('#UserUsername').focus();
                            valid = false;
                        }else{
                            $('#UserLoginForm').find('.error:first').text('');
                        }
                        if(pass == ''){
                            $('#UserLoginForm').find('.error:eq(1)').text('لم تقم بإدخال كلمة المرور ').hide().fadeIn('slow');
                            valid = false;
                        }else{
                            $('#UserLoginForm').find('.error:eq(1)').text('');
                        }
                        return valid;
              });

               $('#UserForgetForm').submit(function(){
                        valid = true;          
                        email    = $('#UserEmail').val();
                        var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
                        
                        if(!filter.test(email)){
                            $('#UserForgetForm').find('.errorE:first').text('لم تقم بإدخال  بريد الكتروني صحيح').hide().fadeIn('slow');
                            $('#UserEmail').focus();
                            valid = false;
                        }else{
                            $('#UserForgetForm').find('.errorE:first').text('');
                        }
                        return valid;
              });
          
            
            $('#emptycart').click(function(){
               if( !confirm('هل حقا تريد إفراغ السلة ؟')) return false;
               $('.loader').fadeIn(500);
               azd.dCart = Array();
               azd.btn();
               setup.pCart = Array();
               setup.addToCart();               
               $('.loader').fadeOut(500);
               
            });
            
            
            /* event submit form domaine */
            $('#domaineCheckForm').submit(function(){
                return false;   
            })                         
    },
    btn:function(){
                azd.count = 0;
                x = azd.dCart.length;
                /* all check  */
                $('.check').each(function(){
                    if($(this).attr('value') == 1){
                        value  = $(this).attr('domain') + ':'  + $(this).attr('price') + ':' + $(this).attr('currency');
                        if( $.inArray(value,azd.dCart) == -1){
                            azd.dCart[x] = value;    
                            x++;
                        }                        
                    }
                });
                azd.count = x;
                azd.xCart();
                azd.remove();
                azd.addCart();
    },
    // show cart
    xCart:function(){
        $('#cartDomain').empty();       
        for(i=0;i<azd.dCart.length;i++){
            domains =  azd.dCart[i].split(":");
            info    = $('<div class="info"></div>');
            remove  = $('<div class="remove" domain="'+ domains[0] +'" currency="'+domains[2]+'"  price="'+domains[1]+'"></div>');
            domain  = $('<div class="domain"></div>');
            dname   = $('<div class="dname">' + domains[0] + '</div>');
            price   = $('<div class="price">' + domains[1] + ' ' + domains[2] + '</div>');
            domain.append(price).append(dname);
            info.append(remove).append(domain);
            $('#cartDomain').append(info.hide().fadeIn('slow').delay(500).slideDown("slow"));
        }
        $("#totalPrice").text(setup.total()+azd.total());
        $("#totalPriceCart").text(setup.total()+azd.total());
    },
    /* function trige end check domains */
    si:function(){
            var c = 0;
            var si = setInterval(function(){
                c++;
                if ( (azd.bool && azd.count ==  azd.lenD) || c== 5 ){
                     azd.bool = false;
                     azd.checkcheckbox();
                     $('.loader').fadeOut(500);
                     $('html,body').animate({scrollTop:140},1000);
                     clearInterval(si);
                }
            },2000);
    },
    checkcheckbox:function(){
        $('#dt').find('.check').click(function(){
            valide  =  azd.webroot + 'img/icons/valide.png';
            checked = azd.webroot + 'img/icons/checked.png';
            if($(this).attr('src') == valide)
            {
                $(this).attr('src',checked);
                $(this).attr('value',1);
            }
            else
            {
                /* value domaine */
                value  = $(this).attr('domain') + ':'  + $(this).attr('price') + ':' + $(this).attr('currency');
                /*  grep item from azd.cart */
                azd.dCart = jQuery.grep(azd.dCart, function(v) {return (v != value && v != undefined);});
                //azd.lc    = azd.dCart.length;
                /* trigger for  update cart */
                $(this).attr('src',valide);
                $(this).attr('value',0);
            }
            azd.btn();
        });
    },
    remove:function(){
        $('.remove').click(function(){  
            valide  =  azd.webroot + 'img/icons/valide.png';
            checked = azd.webroot + 'img/icons/checked.png';
            domain  = $(this).attr('domain');
            value  = $(this).attr('domain') + ':'  + $(this).attr('price') + ':' + $(this).attr('currency');
            azd.dCart = jQuery.grep(azd.dCart, function(v) {return (v != value && v != undefined);});
            $('#dt').find('.check').each(function(){
                if($(this).attr('domain') == domain)
                {
                   $(this).attr('src',valide);
                   $(this).attr('value',0);
                }
            });   
            azd.xCart();
            azd.remove();
            azd.addCart();
        })
    },
    /* remove attr checked */
    checkbox:function(){
         $('input:checkbox[name="data[domaine][extension][]"]:checked').each(function(index){
                $(this).removeAttr("checked");
         });
         $('input:checkbox[name="data[domaine][extension][]"]:disabled').each(function(){
                $(this).removeAttr("disabled");
            });
         $('#xis').fadeOut('500').empty();
         $('#dt').fadeOut().empty();
         azd.count =  0;
         azd.bool  = true;
    },
    /* send all extension to check */
    domainF:function(){
        azd.i         = false;
        i             = 1;
        $('input:checkbox[name="data[domaine][extension][]"]').each(function(){
                azd.extension = $(this).next().text();
                azd.domain    = azd.name + azd.extension;   
                azd.id        = $(this).val();
                if($.inArray(azd.domain,azd.domains) == -1){
                    $(this).attr('disabled','');
                    $('.loader').fadeIn(500);    
                    azd.domains[i] = azd.domain;
                    azd.check();
                    i++;
                }
                if(azd.id = 1){
                    $('#dt').hide().fadeIn('slow');
                }  
        });
            
    },
    log:function(){
        console.clear();
        setInterval(function(){
            for(var i=0;i<azd.dInter.length;i++ ){
                console.log(azd.dInter[i]+' => is Inter ' + i);
            }
            for(var i=0;i<azd.dCart.length;i++ ){
                console.log(azd.dCart[i]+' => is in cart ' + i);
            }
        },2000);
    },
    check:function(){
            $.post(azd.webroot + 'DomainCheck',{domain:azd.domain,i:azd.i,id:azd.id},function(data){
                if(data.xis != undefined){
                    $('#xis').html(data.xis).stop(true, true).fadeIn('slow');
                }
                if(data.table != undefined){
                    azd.count++;
                    $('#dt').append(data.table); 
                }
            },'json');
    },
    addCart:function(){
        $.post(azd.webroot + 'DomaineaddToCart',{dCart:azd.dCart,type:'add',len:azd.dCart.length},function(data){            
                azd.dCart = data.dCart;
                $('html,body').animate({scrollTop:200},1000).animate({scrollTop:0},500,'easeOutBack');
          },'json');
    },
    checkCart:function(){
        $.post(azd.webroot + 'DomaineaddToCart',{type:'check'},function(data){            
                azd.dCart = data.dCart;                    
                azd.xCart();
                azd.remove();
                $('html,body').animate({scrollTop:200,top:0},800).animate({scrollTop:0},{duration: 'slow',easing: 'easeOutBack'});
         },'json');
    },
    total:function(){
            total = 0;
            for(var i=0;i<azd.dCart.length;i++ ){
              total += parseInt(azd.dCart[i].split(':')[1]);
            }   
            return total;
    }
}


setup  = {
    pCart:{type:null},
    webroot:null,
    init:function(webroot){
        setup.webroot = webroot;
        setup.checkCart();
         /* order setups to cart */
        $('.order').click(function(){
            inArray     = false;
            value       = {name:$(this).attr('name'),price:$(this).attr('price'),currency:$(this).attr('currency') ,id:$(this).attr('id'),type:$(this).attr('type')};
            x = setup.pCart.length;
            $('html,body').animate({scrollTop:200},1000).animate({scrollTop:0},500,'easeOutBounce','easeInOutCirc');
             $.each(setup.pCart, function(i,item){
                 if(item.id == value.id && item.type == value.type) inArray = true;
             });
             if(!inArray){
                    setup.pCart.push(value);
                    setup.addToCart();
                    setup.xCart();
                    setup.remove();
             }else{
                 alert('سبق وان تمت اضافته الى السلة');
             }
        })
    },
    addToCart:function(){
          $.post(azd.webroot + 'ServiceaddToCart',{pCart:setup.pCart,type:'add','len':setup.pCart.length},function(data){
              setup.pCart = data.pCart;
          },'json');
    },
    remove:function(){
        $('.remove').click(function(){
            
            value       = {name:$(this).attr('name'),price:$(this).attr('name'),currency:$(this).attr('currency') ,id:$(this).attr('id'),type:$(this).attr('type')};
            //alert(value.type != v.type && value.id != v.id);
            
             setup.pCart = jQuery.grep(setup.pCart, function(v) {
                        return !(value.id ==  v.id  && value.type ==  v.type);
                });
            setup.addToCart();
            setup.xCart();
            setup.remove();
            //$('html,body').animate({scrollTop:200},1000).animate({scrollTop:80},500,'easeOutBounce','easeInOutCirc');
         
        });
    },
    xCart:function(){
        $('#cartObj').empty();   
        for(i=0;i<setup.pCart.length;i++){
            obj    =  setup.pCart[i];
            info   = $('<div class="info"></div>');
            remove = $('<div class="remove"  name="'+ obj.name +'" currency="' + obj.currency + '"  price="' + obj.price + '" id="'+ obj.id +'" type="'+ obj.type +'"></div>');
            objtag = $('<div class="Obj"></div>');
            name   = $('<div class="pname">' + obj.name + '</div>');
            price  = obj.price  +' '+ obj.currency;
             if (!parseInt(obj.price) > 0){
                price  = obj.price;
            }
            price  = $('<div class="price">' + price + '</div>');
            
            info.append(remove).append(objtag.append(price).append(name))
            
            $('#cartObj').append(info.hide().fadeIn('slow').delay(500).slideDown("slow"));

        }
        $("#totalPrice").text(setup.total()+azd.total());
        $("#totalPriceCart").text(setup.total()+azd.total());
    },
    checkCart:function(){
        $.post(azd.webroot + 'ServiceaddToCart',{type:'check'},function(data){            
                if( data.pCart != undefined){
                    setup.pCart = data.pCart;                    
                    setup.xCart();
                    setup.remove();
                }
         },'json');
    },
    total:function(){
            total = 0;
            for(var i=0;i<setup.pCart.length;i++ ){
              pi  = parseInt(setup.pCart[i].price);
              if(pi > 0) total +=pi;
            }   
            return total;
    }
    
}

$(function(){   
    azd.init('/');
    setup.init('/');
    
    $(".close").click(function () {$(this).parent().fadeTo(400, 0, function () {$(this).slideUp(400);});return false;});
    
})


