// Setup global default AJAX settings for requests
$.ajaxSetup({
    async: true,
    cache: false,
    contentType: "application/x-www-form-urlencoded",
    error: defaultAjaxError,
    type: "POST"
});
// Default error callback funciton for AJAX request
function defaultAjaxError(XMLHttpRequest, textStatus, errorThrownt){
    if(errorThrownt){
        alert("AJAX ERROR! "+errorThrownt);
    }else{
        alert("AJAX ERROR!");
    }
    if(confirm('Do you want to see request responce?')){
        alert(XMLHttpRequest.responseText);
    }
}
// Default success callback funciton for AJAX request
function defaultAjaxSuccess(){
    alert("Success!");
}
//Show loading process
function showLoading(id,inc){
    if(!inc){
        $("#"+id).hide();
        $("#"+id).after("<img src='images/ajax-loader.gif' id='status-loading'>");
    }else{
        $("#"+id).html("<img src='images/ajax-loader.gif' id='status-loading'>");
    }
}
//Hide loading proccess
function hideLoading(id){
    $("#"+id).show();
    $("#status-loading").remove();
}
// Show error message
function showError(formId){
    hideError();
    $.get("ui.php?action=error",function(html){
        $("#"+formId).before(html);
    });
}
// Show confirm message
function showConfirm(formId,txt,module,fadeout){
	$("#confirm_box").remove();
    if(txt){
        var confirmText = translate(txt,module);
    }else{
        var confirmText = translate("Your changes successfully saved.","common");
    }
    if(!fadeout){
        fadeout = 2000;
    }
    hideError();
    $.get("ui.php?action=confirm",function(html){
                        $("#"+formId).before(html);
                        $("#confirm_text").html(confirmText);
                        setTimeout(function(){
                            $("#confirm_box").fadeOut();
                        },fadeout);
                    });
}
//Hide error message
function hideError(){
    $("#errorMsg").remove();
}
// Function to display error message and error tooltips for fields with errors
function showFieldsErrors(responce,formId,showErrMsg,type){
    if(showErrMsg == 1){
        showError(formId);
    }
    
    jQuery.each(responce, function(i, val) {
        if(val.valid == false){
            if(!type){
                $("#"+i).addClass("ui-state-error");
                $("#"+i).tooltip({
                    delay: 0,
                    bodyHandler: function(){
                        return val.msg;
                    },
                    id: 'tooltipError',
                    fade: 200
                });
            }else if(type == 1){
                $("#error_"+i).css({display:"block"});
            }else{
                $("#"+i).addClass('errorField');
                if($("#"+i).attr("type") == 'file' || $("#"+i).attr("type") == 'checkbox' || $("#"+i).attr("type") == 'radio'){
                    $("#error_"+i).html(val.msg);
                }else{
                    $("#"+i).val(val.msg);
                }
            }
        }else{
            if(!type){
                $("#"+i).removeClass("ui-state-error");
                $("#"+i).tooltip();
            }else if(type == 1){
                $("#error_"+i).css({display:"none"});
            }else{
                if($("#"+i).attr("type") == 'file' || $("#"+i).attr("type") == 'checkbox' || $("#"+i).attr("type") == 'radio'){
                    $("#error_"+i).html('');
                }
                $("#"+i).removeClass('errorField');
            }
            
        }
    });
}

//Function for translating
function translate(msg,m){
    var t = $.ajax({
            async: false,
            url: "ui.php",
            data: "action=translate&s="+msg+"&m="+m
        }).responseText;    
    
    return t;
}

function popup(url,w,h){
    myWindow = window;
    myWindow.open(url,'Popup','width='+w+', height='+h+', scrollbars=no, resize=no, titlebar=no, toolbar=no, location=no');
}

function refreshCaptcha(){
    $("#captcha").attr('src','captcha.php?'+Math.random());
}
//Redirect function
function redirect(url){
    location.href = url;
}
// Clear form
$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

//Hover state for all buttons 
$(document).ready(function(){
        $("input[type='button'],input[type='submit'],input[type='reset'],#dialog_link,a[class*='dialog_link']").mouseover(
                function(){
                    $(this).toggleClass('ui-state-hover');
                }
        ).mouseout(
                function(){
                    $(this).toggleClass('ui-state-hover');
                }
        );
    }
);

function dataTablesConfigure(){
    var lastColumn = $(".ui-datatable thead").find("th").length - 1;
    var columnDefs = new Array();
    $(".ui-datatable th").each(function(index){
        if($(this).hasClass('center')){
            columnDefs.push({ "sClass": 'center', "aTargets": [ index ] });
        }
        if($(this).hasClass('nonSearchable')){
            columnDefs.push({ "bSearchable": false, "aTargets": [ index ] });
        }
        if($(this).hasClass('nonSortable')){
            columnDefs.push({ "bSortable": false, "aTargets": [ index ] });
        }
    });
    var oTable;
    var gaiSelected =  [];
    options = new Object();
    if($(".ui-datatable").hasClass('serverside')){
        options = {
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "bAutoWidth": true,
            "bInfo": true,
            "bLengthChange": true,
            "iDisplayLength": 10,
            "bPaginate": true,
            "bProcessing": true,
            "bSort": true,
            "bSortClasses": true,
            "bStateSave": true,
            //"sScrollX": "100%",
            "bScrollCollapse": true,
            //,"sScrollY": "100px"
            "iCookieDuration": 60*60*24, /* 1 day */
            "aoColumnDefs": columnDefs,
            "oLanguage": {
                "sUrl": "lang/icelandic/dataTable.txt"
            },
            "bServerSide": true,
            "sAjaxSource": $("#script_name").val(),
            "fnServerData": function ( sSource, aoData, fnCallback ) {
                /* Add some extra data to the sender */
                aoData.push( { "name": "action","value": "load_items_list" } );
                $.getJSON( sSource, aoData, function (json) { 
                    /* Do whatever additional processing you want on the callback, then tell DataTables */
                    fnCallback(json);
                } );
            },
            "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
                if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
                {
                    $(nRow).addClass('row_selected');
                }
                return nRow;
            }
        };
    }else if($(".ui-datatable").hasClass('clientside')){
        options = {
                "bJQueryUI": true,
                "sPaginationType": "full_numbers",
                "bAutoWidth": true,
                "bInfo": true,
                "bLengthChange": true,
                "iDisplayLength": 10,
                "bPaginate": true,
                "bProcessing": false,
                "bSort": true,
                "bSortClasses": true,
                "bStateSave": true,
                "sScrollX": "100%",
                "bScrollCollapse": true,
                //"bRetrieve": true,
                //,"sScrollY": "100px"
                "iCookieDuration": 60*60*24, /* 1 day */
                "aoColumnDefs": columnDefs,
                "oLanguage": {
                    "sUrl": "lang/icelandic/dataTable.txt"
                },
                "fnRowCallback": function( nRow, aData, iDisplayIndex ) {
                if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
                {
                    $(nRow).addClass('row_selected');
                }
                return nRow;
            }
        };
    }else{
        options = {
                "bJQueryUI": true,
                "bInfo": false,
                "bLengthChange": false,
                "iDisplayLength": 1000,
                "bPaginate": false,
                "bProcessing": false,
                "bSort": false,
                "bFilter": false
            };
    }
    if($(".ui-datatable").length > 0){
    	oTable = $(".ui-datatable").dataTable(options);
    }
    /* Click event handler */
    if($(".ui-datatable").hasClass('serverside')){
        $('.ui-datatable tbody tr').live('click', function () {
            var aData = oTable.fnGetData( this );
            var iId = aData[0];
            
            if ( jQuery.inArray(iId, gaiSelected) == -1 ){
                gaiSelected[gaiSelected.length++] = iId;
            }else{
                gaiSelected = jQuery.grep(gaiSelected, function(value) {
                    return value != iId;
                } );
            }
            $(this).toggleClass('row_selected');
        } );
    }else{
        /* Add a click handler to the rows - this could be used as a callback */
        $('.ui-datatable tbody tr').click( function() {
            if ( $(this).hasClass('row_selected') )
                $(this).removeClass('row_selected');
            else
                $(this).addClass('row_selected');
        } );
    }
}

// Apply Data Tables for table lists
$(document).ready(function(){
    dataTablesConfigure();
    configureDateTimePicker();
});

//Datetime picker
function configureDateTimePicker(){
	$.datepicker.setDefaults($.datepicker.regional['is']);
	if($(".datetimepicker").length > 0){
		$(".datetimepicker").datetimepicker({
	        showOn: "button",
	        buttonImage: "images/calendar.gif",
	        buttonImageOnly: true,
	        dateFormat: "dd.mm.yy",
	        showButtonPanel: true,
	        changeMonth: true,
			changeYear: true
	    });
	}
}

