/*
Ajax request handling
usage:
  froms - class ajax
  href - '#call/call/call:1'
  input call - class ajax - action="call/call"
  select call - class ajax - action="call/call"
  .autocomplete - action="call call"
  .datepicker - no ajax call
  .checkall - no ajax
  .clearonclick - no ajax
    
responses:
  msg
  error
  false
  replace
  hide
  sql
  redirect
  1 (true)
interactions classes...tbc:
  loading
  on load
  on succed
  on error   
  
@todo:
  123                  
*/

//@todo gal padaryti kad automatishkai leibelis sekanchiam formos elementui prisiskirtu... nes dabar tie idai htmle naudojami tik leibeliu ir nafig ...
     
// formu catchinimas
//$.noConflict();
//jQuery.noConflict();
//@revise without document ready will it be better the live or this style......now withou document doesnt work
jQuery(document).ready(function($){ 
    /*parsinam img'us su .gal paruosdami jas fancybox'ui*/
    $("img.gal").each(function(){
        var parent = $(this).parent('a');
        $(this).removeClass('gal');
        if ($(parent).length > 0){ //jei visgi turim priskirtą linką 
            $(parent).addClass('gal').attr('rel', 'gallery'); //pridedam reikiama klase, ir galerija
        }
        else{
            var link = $(this).attr('src');
            $(this).wrap('<a href="'+link+'" class="gal" rel="gallery" />');
        }
    });
        
    //fancy box
        
    $(".gal").fancybox({
        });

    //datepicker sh
    $('.datepicker').live('focus', function() {
        /*  TIPS
          page up/down – previous/next month
          ctrl+page up/down – previous/next year
          ctrl+home – current month or open when closed
          ctrl+left/right – previous/next day
          ctrl+up/down – previous/next week
          enter – accept the selected date
          ctrl+end – close and erase the date
          escape – close the datepicker without selection
          */
        $(this).datepicker({
            dateFormat: 'yy-mm-dd',  
            changeMonth: true
        });
    }).focus();
          
    // formu submitinimas su ajax klase  
    $("body").delegate(".ajax", "submit", function(){
        var $this = $(this);
        //hide all msgs
        hideAllmsgs();
        showLoading($this);
        var action = $this.attr('action');  
        $.post("index.php", $(this).serialize() + '&action='+ action + '&type=ajax',
            function(data){
                //	 		  msg(data);       	
                if (data){
                    //   		 		        var JSON_array = eval(( "(" + data + ")" )); //@revise stabdymas ir saugumas del eval
                    var JSON_array = jQuery.parseJSON( data ); //shitas naudoja ta pati eval                     		 		        
                    process(JSON_array, $this);                  
                }                  
                doneLoading($this);
            });
              
             
        return false;  
    });
  
      
    //do ajax a href handling //@revise selector
 /*   $("body").delegate("a[href*=#]", "click", function(){
        //@todo second third etc. parameter
        var $this = $(this);        
        var target = $(this).attr("href"); //@revise hash and so on... maybe without hash but with class...          
        target = target.slice(1);
        hideAllmsgs();
        showLoading($this);
          
        if (target == ''){
            return false; // jei nieko nera tai ka chia mes submitinsime... datepicker issue
        }
                          
        $.post("index.php", '&action=' + target  + '&type=ajax',
            function(data){
                //msg(data);       		 	
                if (data){
                    //var JSON_array = eval(( "(" + data + ")" )); //@revise stabdymas ir saugumas del eval
                    var JSON_array = jQuery.parseJSON( data );
                    process(JSON_array, $this);                  
                }                  
                doneLoading($this);
            });         
                        
        return false;
    });         */
     
    $("body").delegate("select[class='ajax']", "change", function(){
        //@todo notifications working with select in the form e.g.
        //alert('test2'); 
        var $this = $(this);
        var name = $(this).attr("name");
        var value = $(this).attr("value");
        var action = $(this).attr("action");
        //msg(action);
        hideAllmsgs();
        showLoading($this);               
        //pavadinimas (name) kaip actionas, ir dar priskiriamas kaip kintamasis su reikshme zhiureti 'cart'                    
        $.post("index.php", '&action=' + action  + '&type=ajax&' + name + '=' + value,
            function(data){
                //msg(data);       		 	
                if (data){
                    //var JSON_array = eval(( "(" + data + ")" )); //@revise stabdymas ir saugumas del eval
                    var JSON_array = jQuery.parseJSON( data );
                    process(JSON_array, $this);                  
                }                  
                doneLoading($this);
            });                                        
        return false;
    });
      
    //checking all table checkboxes
    $("body").delegate(".checkAll", "change", function(){
        var checked_status = this.checked;
        //@todo normalu selecta table o ne  visame puslapyje
        //nors gal ir gerai jei klase reikia priskirineti... odnako...
        $('.check').each(function()
        {      				  
            this.checked = checked_status;
        });
        return false;
    });
      
      
    //AUTOCOMPLETE 
    //priskiria value sekanchiam input elementui
    $("body").delegate("input[class='autocomplete']", "focus", function(){
        //@todo notifications working with select in the form e.g. and e.g. autocomplete
        //@todo neveikia ant clearonclick
        var $this = $(this);
        var name = $(this).attr("name");
        var value = $(this).attr("value");
        var action = $(this).attr("action");
        //msg(action);
        //   hideAllmsgs();
        showLoading($this);        
        
        //@revise visa autocomplete'a nes per daug uzhklausu ir nenusitraukia kitos ir t.t. ir pan.        
        $( $this ).autocomplete({ 
            delay: 150,
            //  autoFocus: true, //problemos del automatinio nustatymo greitai taipant atsiranda
            source: function( request, response) {
            $.post("index.php", '&action=' + action + '&type=ajax&search='+request.term,
                function(data){  
                var data = jQuery.parseJSON( data ); //shitas naudoja ta pati eval               		 	     
                response(data.list);
                doneLoading($this);
                });
            },
            minLength: 2,
            select: function(event, ui) {
            $( $this ).val( ui.item.label);
            $($this).next('input').val( ui.item.id);            
            return false;
            }
            }).data("autocomplete")._renderItem = function( ul, item ) {
            return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>"+ item.html + "</a>" )
            .appendTo( ul );
        };
    });
                       

      
    //focus blur clear blabla
    $("body").delegate(".clearonclick", "focus", function(){
        var last_value = this.value;
        this.value = ''; 
        $(this).blur(function() {

            if (this.value == ''){
                this.value = last_value;
            }
            $(this).unbind('blur'); //tam kad pakeistoji reiksme nebutu tvarkoma su last_Value or so             
        });
    });

    /*truputi papildyta pries tai esanti funkcija*/
    $("input.search").focus(function(){

        var default_value = $(this).attr('default');
        
        if( $(this).val() == default_value){
            $(this).val('');
        }
        
        $(this).blur(function() {

            if ($(this).val() == ''){
                $(this).val(default_value);
            }
            $(this).unbind('blur');
        });
        
    });

});	

function search_form(){
    var input = $('input.search');
        if ($(input).attr('default') != $(input).val()){
            $('form.search_form').submit();            
        }else{
            return false;
        }
}

//show loading
function showLoading($this){
    //alert($this);
    $('.sending', $this).show();
    
    $('.hide_onload', $this).hide();     
    $('.show_onload', $this).show();
    
    $('#exit_loading').attr('src', 'img/logout_loading.gif');
}
//done loading
function doneLoading($this){
    $('.sending', $this).hide();

    //  $('.hide_onload', $this).show();     
    $('.show_onload', $this).hide();

    $('#exit_loading').attr('src', 'img/logout.png');
}

function hideAllmsgs(){
    $('.error_report').hide();
    $('.error').removeClass('error');
}

function reportOk($this){
    $('.ok', $this).show();
    //  
    $('.hide_onsucceed', $this).hide();
    $('.show_onsucceed', $this).show();    
//  
}

function reportError($this){
    $('.hide_onerror', $this).hide();
    $('.show_onerror', $this).show();    
// $('.show_onsucceed', $this).hide();
}


// feedbacko parsinimas
function process(data, $this){ 

    if (data == 1){ //vienas reiksti turetu jog viskas chiki....
        reportOk($this);
    //   return false;
    }
    if (data.error){ //rodome errorus   
        var focus_target = false;
        $.each(data['error'], function(index, data) {
            //focus first form input error element
            if (focus_target == false){   //pirmas bus tas kuris pirmas pagal eilishkuma php...
                $("." + index, $this).focus();
                focus_target = true;
            }
            //show error message
            $(".error_" + index, $this).fadeIn('slow', function() {    });    
            $("." + index, $this).addClass( "error" );        
        //extra shit
        
        //             
        });
        reportError($this);
        return false; //nes erroras yra erroras... ir nereikia ten kitu interpretaciju daryti    
    } 
    if(data.redirect){
        self.location = data.redirect; 
    }
    if(data.msg){ //palaiko kolkas tik viena msg
        msg(data.msg); 
    }
    if(data.freak_form){
        freak_form(data.freak_form, 1);   
    }
    if(data.freak_show){
    //freak_show(data.freak_show);    
    }   
    if (data.content){
        $('#content').html(data.content);
    }    
    if(data.replace){    
        $.each(data['replace'], function(index, data) {
            $('#' +index).hide('fast'); //for fun
            $('#' +index).html(data);
            $('#' +index).fadeIn('slow'); //for fun             
        });
    //@todo append
    //@todo prepend
    //@todo hide inputfiels... for view edit stuff... ???
    //@todo evaluate for js evaluation from php... uh muh... eval()
    //@todo show freak form with data...
    
    }
    if (data.sql){
        sqlError(data);
    }
    if(data.hide){
        $.each(data['hide'], function(index, data) {
            $('#' +index).hide('slow');                       
        });    
    }
    else{ //jeigu nieko nesuprantam - apsimetam kad viskas ok
        reportOk($this);
    }
    /*
        if(data.append){
        msg('got append');
        
        $.each(data['append'], function(index, data) {
            $('#'+index).append(data); //for testing
            msg ('index '+index + ' data '+ data);
        });
    }     */
    
    return false;
}

// msg funkcija skirta atvaizduoi sistemos praneshimus jei viskas gerai, jos net neturetu lyg ir buti hoh... 
function msg(info){    //@todo two more parameters... 
    //@todo append to new line if msg is visible... with br vieleicht
    //@todo autohide after some time with parameter or no
    //@todo show close button or not to show...
      
    $('#msg').html(info + '<span id="close_msg">Esc or <img src = "img/close.png" /></span>'); //blogas sprendimas su tuo close...
    $('#notification').fadeIn('fast'); //@revise 
  
    $('#close_msg').click(function(){
        $('#notification').fadeOut('slow'); //@revise
    });
    $(document).keydown(function(e){
        if (e.keyCode == 27) { //left pressed 
            $('#notification').hide();
        }
    });
}
// sarashu funkcija
function sqlError(data){
    $('#sql_msg').html(data.sql.msg);
    $('#sql_msg_error').html(data.sql.error);
    $('#sql_error').fadeIn('fast'); //@revise
}


