var userCheckFlag = true;
$( document ).ajaxStart(function() {
    if(userCheckFlag){
        $('body').prepend('<div class="ajaxLayer" style="text-align:center; width:100%;height:100%; position:fixed; z-index:1111; background:#85c420;">\
                                <img style="margin:200px auto;" src="'+$('body').attr('data-baseurl')+'images/ajax-loader.gif" title="Ajax Loader" alt="Ajax Loader" />\
                            </div>');
        $('body .ajaxLayer').css({opacity:'.3'});
    }

    console.log('Ajax Started');
});

$( document ).ajaxComplete(function() {
    console.log('Ajax Complete');
    $('body .ajaxLayer').remove();
});

$( document ).ajaxSuccess(function() {
    console.log('Ajax Success');
    $('body .ajaxLayer').remove();
});


$(document).ready(function(){
    if($('.pokeMe').length > 0){
        var poke = $('.pokeMe');
        var timeout = setTimeout(function(){
            poke.animate({opacity:'.0',left:'0px'},3000);
            poke.find('span').animate({fontWeight:"600"},3000,function(){
                poke.remove();
            })    
        },4000);
        
    }
    
    if($(".samPopMsg").length > 0){
        me = $('td.samPopMsg:first');
        me.css({position:'relative'});
        me.append('<p class="samPopMsgCont tal">Double Click to change the counted value</p>');
        me.find('.samPopMsgCont').css({fontSize:'10px',
                                        padding:'5px',
                                        position:'absolute',
                                        left:'0px',
                                        top:'0px',
                                        borderRadius:'7px',
                                        backgroundColor:'#fff'
                                    });
    }

    /* Alert message box start */
	$('.alertbox,.samPopMsgCont').effect( "pulsate", {times:3}, 5000,function(){
		setTimeout(function(){
			$('.alertbox').fadeOut();
		},10000);
        $('.samPopMsgCont').fadeOut().remove();
	});
	/* EOF Alert message box */
	
    /* head popup */
    $("#header .buttons .item > a").click(function(){        
        var popup = $(this).parent('.item').find('.popup');                
        if(popup.length > 0){            
            popup.is(':visible')?popup.fadeOut(200):popup.fadeIn(300);                        
            return false;
        }        
    });
    $(".popup-close").click(function(){
        $(this).parents('.popup').fadeOut(200);
    });
    
        /* load messages in head */
        $("#messages").load('ajax_messages.html');
    
    /* eof head popup */
    
    /* combobox */

    $(".combobox input").focus(function(){   
        var ci = $(this);
        var cb = $(this).parent('.combobox');
            cb.find('ul').show();                    
        
        ci.focusout(function(){        
            setTimeout(function(){                 
                ci.parent('.combobox').find('ul').hide().find('li').show();
            }, 100);        
        });
        
        ci.keyup(function(){
            var cb = $(this).parent('.combobox');
            if(cb.hasClass('ws')){
                if($(this).val().length > 0){
                    cb.find('ul > li').hide();
                    cb.find("ul > li:containsi('"+$(this).val()+"')").show();        
                }else
                    cb.find('ul > li').show();
            }               
        });        
        
        cb.find('li').click(function(){                        
            if($(this).attr('data-val') != null)
                cb.find('input').val($(this).attr('data-val'));
            else
                cb.find('input').val($(this).html());                        
            cb.find('ul').hide().find('li').show();                                    
        });
        
    });
    
    /* EOF combobox */
    
    /* table checkall */
    $("table .checkall").click(function(){           
        var iC = $(this).parents('th').index(); //index of checkall checkbox
        var tB = $(this).parents('table').find('tbody'); // tbody of table        
        
        if($(this).is(':checked'))
            tB.find('tr').each(function(){                
                var cb = $(this).find('td:eq('+iC+') input:checkbox');                
                if(cb.hasClass('uni')) cb.parent('span').addClass('checked');                                
                cb.attr('checked',true);                
            });
        else
            tB.find('tr').each(function(){
                var cb = $(this).find('td:eq('+iC+') input:checkbox');
                if(cb.hasClass('uni'))cb.parent('span').removeClass('checked')
                cb.attr('checked',false);
            });                    
    });
    /* eof table checkall */    
    
    /* icomoon button get code */
    $("#icon_icomoon_list li").click(function(){
       $("#icon_icomoon").html('&lt;i class="'+$(this).find('i').attr('class')+'"&gt;&lt;/i&gt;');
    });
    /* eof icomoon button get code */
    /* glyphs button get code */
    $("#icon_glyphs_list li").click(function(){
       $("#icon_glyphs").html('&lt;i class="'+$(this).find('i').attr('class')+'"&gt;&lt;/i&gt;');
    });
    /* eof glyphs button get code */    
    
    /* Block loading start button  USING FOR EXAMPLE, CAN BE REMOVED*/
    $(".block_loading").click(function(){
        var bC = $(this).parents('.block').find('.content');
        block_loading(bC);
        
        // Timer
        setTimeout(function(){
            block_loading(bC);
        },2000);
        
        return false;
    });
    /* EOF Block loading start button */
    
    /* Remove block button */
    $(".block_remove").click(function(){
        $(this).parents('.block').fadeOut(300,function(){
            $(this).remove();
        });
        return false;
    });
    /* EOF Remove block button */
    
    /* Toggle block button */
    $(".block_toggle").click(function(){
        var bC = $(this).parents('.block').find('.content');
        if(bC.is(':visible')){
            bC.slideUp();
            $(this).find('span').removeClass('i-arrow-down-3').addClass('i-arrow-up-3');
        }else{
            bC.slideDown();
            $(this).find('span').removeClass('i-arrow-up-3').addClass('i-arrow-down-3');
        }
        return false;
    });
    /* EOF Toggle block button */
    
    /* Navigation open submenu button */
    $("#sidebar .navigation li.openable > a").click(function(){        
        if($(this).parent('li').hasClass('open'))
            $(this).parent('li').removeClass('open');
        else
            $(this).parent('li').addClass('open');            
        return false;
    });
    /* EOF Navigation open submenu button */
    
    /* Toggle navigation button */
    if($("body").width() < 769){        
        $("#wrapper").addClass("sidebar_off");
        $(".c_layout").addClass('active').find("span").attr("class","i-layout-9"); 
        
    }
    
    $(".c_layout").click(function(){
        
        if($("#wrapper").hasClass("sidebar_off")){
            $("#wrapper").removeClass("sidebar_off");
            $(this).removeClass('active').find("span").attr("class","i-layout-8");
        }else{
            $("#wrapper").addClass("sidebar_off");
            $(this).addClass('active').find("span").attr("class","i-layout-9");
        }
        
        actions();
        return false;
    });
    /* EOF Toggle navigation button */
    
    /* Toggle layout */
    $(".c_screen").click(function(){                
        
        if($("#wrapper").hasClass("screen_wide")){
            $.cookies.set('c_screen','0');
            $("#wrapper").removeClass("screen_wide");
            $(this).removeClass('active').find("span").attr("class","i-stretch");
        }else{
            $.cookies.set('c_screen','1');
            $("#wrapper").addClass("screen_wide");
            $(this).addClass('active').find("span").attr("class","i-narrow");
        }                        

        actions();
        return false;        
    });
    /* EOF Toggle layout */
    
    /* input file */
    $(".file .btn, .file input:text").click(function(){        
        var block = $(this).parent('.file');
        block.find('input:file').click();
        block.find('input:file').change(function(){
            block.find('input:text').val(block.find('input:file').val());
        });
    });
    /* eof input file */     
        
    /* Draggable blocks */        
    if($(".sortableContent").length > 0){

        var scid = 'sC_'+$(".sortableContent").attr('id');
                
        var sCdata = $.cookies.get( scid );          
        
        if(null != sCdata){            
            for(row=0;row<Object.size(sCdata); row++){                
                for(column=0;column<Object.size(sCdata[row]);column++){                    
                    for(block=0;block<Object.size(sCdata[row][column]);block++){                        
                        $("#"+sCdata[row][column][block]).appendTo(".sortableContent .scRow:eq("+row+") .scCol:eq("+column+")");                        
                    }
                }               
            }            
        }                    
       
        //$.cookies.del( scid );
       
        $(".sortableContent .scCol").sortable({
            connectWith: ".sortableContent .scCol",
            items: "> .block",
            handle: ".head",
            placeholder: "scPlaceholder",
            start: function(event,ui){
                $(".scPlaceholder").height(ui.item.height());
            },
            stop: function(event, ui){                                

                var sorted = {};
                var row = 0;
                $(".sortableContent .scRow").each(function(){                    
                    sorted[row] = {};
                    $(this).find(".scCol").each(function(){
                        var column = $(this).index();                        
                        sorted[row][column] = {};

                        $(this).find('.block').each(function(){
                            sorted[row][column][$(this).index()] = $(this).attr('id');
                        });
                    });
                    row++;
                });
                                                
                $.cookies.set( scid, JSON.stringify(sorted));                
            }
        }).disableSelection();
    }
    
    /* EOF Draggable blocks */            
    
    /* pricing table */
    $("#pricing_action").on('change',function(){
        if($(this).val() == 1)
            $("#pricing_domain").hide();
        else
            $("#pricing_domain").show();
    });
    /* EOF pricing table*/
    
    /* Settings */
        var sTheme = $.cookies.get('sTheme');
        if(null != sTheme){
            $(".themes a[data-theme="+sTheme+"]").addClass('active');
            $("body").addClass(sTheme);
        }else            
            $(".themes a.default").addClass('active');
        
        $(".themes a").click(function(){
            $(".themes a").removeClass('active');
            $(this).addClass('active');
            $('body').removeClass('themeSimple themeDark').addClass($(this).attr('data-theme'));
            $.cookies.set('sTheme',$(this).attr('data-theme'));
            return false;
        });
        
        var sBack = $.cookies.get('sBack');
        if(null != sBack){
            $(".backgrounds a[data-back="+sBack+"]").addClass('active');
            $("body").addClass(sBack);
        }else            
            $(".backgrounds a.default").addClass('active');
        
        $(".backgrounds a").click(function(){
            $(".backgrounds a").removeClass('active');
            $(this).addClass('active');
            $('body').removeClass('b_bcrosshatch b_crosshatch b_cube b_dots b_grid b_hline b_simple b_vline').addClass($(this).attr('data-back'));
            $.cookies.set('sBack',$(this).attr('data-back'));
            return false;
        });    
    /* EOF Settings */

    /*user online status check*/
    checkUserOnlineStatus();
    setInterval(checkUserOnlineStatus, 500000);
    /*user online status check*/

    /********************************increment idle time of user*******************/
    /*************************************Sayem(21-11-2014)************************/
    var idleInterval = setInterval(timerIncrement, 60000);
    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });


    /********************************Enable print screen modification option*******/
    /******************************Sayem (18-5-2015)*******************************/
    printModCont();
});
$(window).load(function(){      
    $(window).resize();
});
$(window).resize(function(){ 
    if($('.image').length){
        $('.image').width($('.image').parents('td').width());
        $('.image').height($('.image').parents('td').find('table tr:first').height());
    }
    resizing();
    actions();    
    thumbs();
    $('.userList').css({"max-height":$(window).height()+"px"});    
});

function checkUserOnlineStatus(){
    if(idleTime < 5){
        userCheckFlag = false;
        $.ajax({
            url: $('body').attr('data-baseurl')+"usersetting/useronlinestatus/",
            async: false,
            dataType: "JSON",
            success: function(data) {
                if(data.length > 0){
                    /*$('.wrap').find('.onlineUser')animate({opacity:'0'},500,function(){
                        $(this).remove();
                    });*/
                    var list = '';
                    var i = 0;
                    $.each(data, function(){ 
                        if(data[i].idle < 300){
                            list +='<li class="themes backgrounds" style="padding:5px"><a title="<?php /*Click to poke '+data[i].username+'*/ ?>" onclick="poke('+data[i].fldid+')" href="javascript:" class="btn-language tal" style="width:90% !important; height:auto !important;">'+
                                        data[i].username+
                                    '<span style="display:block;">('+data[i].access_comp+')</span></a></li>';
                        }
                        else{
                            list +='<li class="themes backgrounds" style="padding:5px"><a title="<?php /*Click to poke '+data[i].username+'*/ ?>" onclick="poke('+data[i].fldid+')" href="javascript:" class="btn-language tal" style="width:90% !important; height:auto !important; background:#b4e664">'+
                                        data[i].username+
                                    '<span style="display:block;">('+data[i].access_comp+')</span></a></li>';                                
                        }                    
                        i++;
                    });
                    $('body .wrap:first').find('.onlineUser').animate({opacity:'0'},1000,function(){
                        $(this).remove();
                    });
                    $('body .wrap:first').append(' <div class="buttons fr onlineUser">'+
                                    '<div class="item">'+
                                        '<div class="btn-group">'+
                                            '<a href="#" class="btn-header btn-resize dropdown-toggle" data-toggle="dropdown" title="user information">'+            
                                                '<b style="font:bold 15px/18px Tahoma, Arial, sans-serif; border:2px solid;border-radius: 10px;padding:0 3px;">'+
                                                    data.length+
                                                '</b>'+
                                            '</a>'+
                                            '<ul class="dropdown-menu userList" style="overflow:scroll;">'+
                                                '<li class="themes backgrounds">'+
                                                    list+
                                                '</li>'+
                                            '</ul>'+
                                        '</div>'+
                                    '</div>'+
                                '</div>');        
                }
                userCheckFlag = true;
            } //end success
        }); //end ajax
    }
} 


//********************************Sayem (23-12-2014)************************************//
//**************************************Poke********************************************//
function poke(whom){
    $.ajax({
            url: $('body').attr('data-baseurl')+"usersetting/poke/",
            async: false,
            data: {
                    whom:whom
                },
            type: "POST",
            dataType: "JSON",
            success: function(data) {
                console.log(data);
                if(data == 'me'){
                    alertbox("You can't poke yourself !",3);
                }
            }
    });
}

function getPoke(){
    $.ajax({
            url: $('body').attr('data-baseurl')+"usersetting/getPoke/",
            async: false,
            type: "POST",
            dataType: "JSON",
            success: function(data) {
                console.log(data);
                /*if(data == 'me'){
                    alertbox("You can't poke yourself !",3);
                }*/
            }
    });    
}
//********************************Sayem (21-11-2014)************************************//
//**************************User active in page status********************************//
var idleTime = 0;
function timerIncrement(){
    idleTime++;
}

//**************************Dynamic alert box********************************//
//***************************Sayem (3-9-2014)********************************//
//Alert message box
function alertbox(msg,mode,callBack){

    if(!$(".sambox").length){
        $('.block:first').prepend('<div class="content sambox" style="display: none;">\
                                <div class="row-fluid">\
                                    <div class="span12">\
                                        <div class="alert" style="font-size:20px !important;">\
                                            <strong>Success! </strong>\
                                        </div>\
                                    </div>\
                                </div>\
                            </div>'
                    );
    }

    $('.sambox .alert').removeClass('alert-error').removeClass('alert-success');
    if(mode == 1)
        $('.sambox .alert').addClass('alert-success').html("<strong>Success! </strong>"+msg);
    else if(mode == 2)
        $('.sambox .alert').addClass('alert-error').html("<strong>Error! </strong>"+msg);
    else
        $('.sambox .alert').html("<strong>Warning! </strong>"+msg);
    $('.sambox').show();

    $('.sambox').effect( "pulsate", {times:3}, 5000,function(){
        setTimeout(function(){
            $('.sambox').fadeOut();
            if(callBack)
                callBack();
        },10000);   
    });


    $('html,body').animate({
       scrollTop: $('.sambox').offset().top
    });
}

//***********************GST Registration check******************************//
//***************************Sayem (3-9-2014)********************************//
/*
    type = Either 'customer' or 'supplier'
    id = id for the repective transaction
*/
function isGstRegistered(id,type){
    var returnType = false;
    if(typeof id == 'undefined' || typeof type == 'undefined'){
        alert("Transaction ID not found");
        return false;
    }
    $.ajax({
        url: $('body').attr('data-baseurl')+"aptransaction/getGSTInfo",
        async: false,
        type: "POST",
        data: "ID="+id+"&type="+type,
        dataType: "JSON",
        success: function(data) {
            if(data == true){
                console.log('um true');
                returnType = true;
            }else{
                console.log('um in else');
                returnType = false;
            }

        }
    });
    return returnType;
}
//***********************Financial year validation***************************//
//***************************Sayem (18-8-2014)*******************************//
function finanEngine(className){
	var returnType = false;
	if($('.'+className).length){
		$.ajax({
			url: $('body').attr('data-baseurl')+"glsetting/financialYearCloseChk/",
			async: false,
			type: "POST",
			data: 'date='+$('.'+className).val(),
			dataType: "html",
			success: function(data) {
				var obj = jQuery.parseJSON(data);
				
				if(obj[0] == 'false'){
					var currentDate = new Date();
					var day = currentDate.getDate();
					var month = currentDate.getMonth() + 1;
					var year = currentDate.getFullYear();
					$('.'+className).val(day + "-" + month + "-" + year);
					//alert("The financial date you choose is either closed or not exists");
					finandterr(className,true);
				}else{
					finandterr(className,false);
					returnType = true;
				}
			} //end success
		}); //end ajax
	}else{
		returnType = true;		
	}
	return returnType;
}

//financial year error message
function finandterr(className,mode){
	if(mode){
		$('.'+className).parent().css('position','relative').append('<div class="customerformError parentFormSaleDetailForm formError finanError" style="opacity: 0.87; position: absolute; top: 35px; left: 107px; margin-top: 0px;"><div class="formErrorArrow formErrorArrowBottom"><div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div></div><div class="formErrorContent">* The financial date you choose is either <br />closed or not exists<br></div></div>');
		$('html,body').animate({scrollTop: $('.'+className).offset().top},'slow');
	}else{
		$('.'+className).parent().find('.finanError').remove();
	}
}

function resizing(){        

    if($("body").width() < 1025){
        $(".c_screen").hide();                    
        $("#wrapper").addClass("screen_wide");
    }else{
        $(".c_screen").show();
        if(!$(".c_screen").hasClass('active'))           
           $("#wrapper").removeClass("screen_wide");
       
       if($.cookies.get('c_screen') == '1')
           $("#wrapper").addClass("screen_wide");
    }    
        
}

//***********************Print content modification***************************//
//***************************Sayem (18-5-2014)*******************************//
function printModCont(){
    if($('.modPrint').length > 0){
        var stay = true;
        $('.modPrint').css('position','relative').prepend('<button style="display:none; position:absolute;right:0;top:-20px;" title="Remove" class="btn-print-remove btn-icon btn-danger-form btn-mini no-print" type="button" name="Remove"><i class="icon-remove-sign"></i></button>');
        $('.modPrint').hover(function(e){
            stay = true;
            var me = $(this);
            var pos = $(this).position();
                    me.find('.btn-print-remove').css({display:'block',left:(e.pageX-pos.left)+'px',right:(e.pageY-pos.top)+'px'});
                    if(me.find('.btn-print-remove').length >0){
                        me.find('.btn-print-remove').on('click',function(e){
                            e.preventDefault();
                            if(!me.hasClass('no-print')){
                                me.css('text-decoration','line-through').addClass('no-print');
                                me.find('.btn-print-remove').css('display','none');
                            }else{
                                me.css('text-decoration','none').removeClass('no-print');
                                me.find('.btn-print-remove').css('display','none');
                            }
                        });
                    }
        },function(e){
            var me = $(this);
            me.find('.btn-print-remove').css('display','none');
        });

        
    }
}
//***********************Print content modification***************************//
function actions(){
    block_items_width('.wide_elements',['.add-on','button'],'input');    
    if($(".gallery").length > 0) gallery();    
}

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function block_loading(content){
    /*if(content.find('.block_loading').length > 0)
        content.find('.block_loading').remove();
    else{
        var ptc = content.hasClass('np') ? 0 : 20;
        content.append('<div class="block_loading" style="width: '+(content.width()+ptc)+'px; height: '+(content.height()+ptc)+'px;"><img src="img/loader.gif"/></div>');
    }
    return false;*/
}

function block_items_width(block,what,to){    
    
    $(block).each(function(){        
        var iWidth = $(this).width();        
        if(what.length > 0){            
            for(var i=0; i < what.length; i++){
                $(this).find(what[i]).each(function(){                    
                    iWidth -= $(this).width()+(parseInt($(this).css('padding-left')) * 2)+2;
                });
            }            
            $(this).find(to).width(iWidth-12);
        }
    });    
    
}

function gallery(){   
    
    var w_block = $(".gallery").width()-20;
    var w_item  = $(".gallery a").width();        
    var c_items = Math.floor( w_block/w_item );    
    var m_items = Math.round( (w_block-w_item*c_items)/(c_items*2) );        
    $(".gallery a").css('margin',m_items+2);
}

function thumbs(){
    
    $(".thumbs").each(function(){        
        
        var maxImgHeight = 0;
        var maxTextHeight = 0;    
        
        $(this).find(".thumbnail").each(function(){
            var imgHeight = $(this).find('a > img').height();
            var textHeight = $(this).find('.caption').height();
            
            maxImgHeight = maxImgHeight < imgHeight ? imgHeight : maxImgHeight;
            maxTextHeight = maxTextHeight < textHeight ? textHeight : maxTextHeight;
        });
        
        $(this).find('.thumbnail > a').height(maxImgHeight);
        $(this).find('.thumbnail .caption').height(maxTextHeight);
    });
    

    
    var w_block = $(".thumbs").width()-20;
    var w_item  = $(".thumbs .thumbnail").width()+10;
    
    var c_items = Math.floor(w_block/w_item);
    
    var m_items = Math.floor( (w_block-w_item*c_items)/(c_items*2) );
    
    $(".thumbs .thumbnail").css('margin',m_items+2);

}

function clear_form(form) {
    $(form).find(':input').each(function(){        
        switch(this.type) {            
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                if(!$(this).is(':disabled'))
                    $(this).val('');            
            break;
            case 'checkbox':
            case 'radio':
                if(!$(this).is(':disabled')){                    
                    $(this).attr('checked', false);
                    if($(this).hasClass('uni'))
                        $(this).parent('span').removeClass('checked');                    
                }
            break;
        }        
    });
    return false;
}

//On blur format input field number (Sayem-1-4-2015)
function formatme(me){
    var $num = $(me).val().replace(/,/g, "");
    $num = Number($num).toFixed(2);
    $(me).val(("" + $num).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function($1) { return $1 + "," }));
}

//Number formating for thousand separator(Sayem-20-8-2014)
function formatNumber(num){
    return ("" + num).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, function($1) { return $1 + "," });
}


//increase input field size
$(document).ready(function(){
    /*$('table tbody td input').focus(function(){
        $(this).attr('data-prevwidth',$(this).width);
        console.log($(this).width);
    }); */   
});

//Increase input field size during input (sam-12-12-2014)
$(document).on('focus',"table tbody td input:text",function(){
    if($(this).outerWidth( true ) < 100){
        var tbody = $(this).parents('tbody');
        if($(this).parents('tbody').find('tr').not('#trInfos,#trInfosCharge').length > 1){
            var elmIndex = $(this).parents('tr').find('td').index($(this).parents('td'))+1;
            tbody.find('tr td:nth-child('+elmIndex+') input').attr('data-prevwidth',$(this).outerWidth( true )+"px").animate({width:'100px'},300);
        }else{
            $(this).attr('data-prevwidth',$(this).outerWidth( true )+"px").animate({width:'100px'},300);
        }
    }
});
$(document).on('blur',"table tbody td input:text",function(){
    
    var tbody = $(this).parents('tbody');
    if($(this).parents('tbody').find('tr').not('#trInfos,#trInfosCharge').length > 1){
        var elmIndex = $(this).parents('tr').find('td').index($(this).parents('td'))+1;
        tbody.find('tr td:nth-child('+elmIndex+') input').animate({width:$(this).attr('data-prevwidth')},300);
    }else{
        $(this).animate({width:$(this).attr('data-prevwidth')},300);
    }
    
});