// JavaScript Document
// <!--
//var AJAXTimeOutCount = 0;
var ajaxRequest = null;
// Начальная инициализация 
$(document).ready(function() {	
	$('#loginform').submit(function(){
		if (location.pathname != '/') {
			$('#backto').val(location.pathname + '' + location.search);
		}
	});
});


// Глобальные установки для AJAJ запросов
$.ajaxSetup({
	type: "post",
	url : "/index.php",
	cache: false,
	timeout: 60000,
	async : true,
	dataType: "json",
	processData: true,
	success: getAnswer,
	error: getError
});

// Функция посылки AJAJ запросов в административной части системы
function sendAAjax(qString) {
	ajaxRequest = qString;
	if (is_object(ajaxRequest)) {
		ajaxRequest.cond = 'admin';
	} else {
		ajaxRequest = ajaxRequest + '&cond=admin';
	}
	$.ajax({data:ajaxRequest});
}

// Функция посылки AJAJ запросов в сайтовой части системы
function sendAjax(qString) {
	ajaxRequest = qString;
	$.ajax({data:ajaxRequest});
}

// Обработка ошибок полученных при выполнении AJAX запроса 
function getError(XMLHttpRequest, textStatus, errorThrown) {
	if (textStatus == 'parsererror') {
		jAlert('Sorry, could not process the  received data. System error. <br/> Answer: </br> ' + XMLHttpRequest.responseText, 'Error');
	} else if(textStatus == 'timeout') {
		alert('We are sorry, the service is unavailable now. Please, try again later.');
	}
}

// Обработка AJAJ ответа
function getAnswer (msg, error) {
	//AJAXTimeOutCount = 0;
	$.each (msg, function(operation) {
						 
		switch (operation) {
			case 'insertHTML' :
				$.each (msg[operation], function (i, val) {
					 if (val.clean) $(val.path).html(''); 
					 if (val.insert == 'append') $(val.path).append(val.innerHTML);
					 else $(val.path).prepend(val.innerHTML);
				});
			break;
			
			case 'changeClass' :
				$.each (msg[operation], function (i, val) {
					$(val.path).addClass(val.newClass);
				});
			break;
			
			case 'addClass' :
				$.each (msg[operation], function (i, val) {
					$(val.path).addClass(val.addClass);
				});
			break;
			
			case 'removeClass' :
				$.each (msg[operation], function (i, val) {
					$(val.path).removeClass(val.removeClass);
				});
			break;
			
			case 'showElement' :
				$.each (msg[operation], function (i, val) {							  
					 if (val.effect != '') {
						switch (val.effect) {
							case 'slideDown' :
								 $(val.path).slideDown(300);
							break;
							case 'fadeIn' : 
								$(val.path).fadeIn(300);
							break;
							default:
								$(val.path).show();	
							break;
						}	
					 } else {
					 	$(val.path).show();
					 }
				});			
			break;
			
			case 'hideElement' :
				$.each (msg[operation], function (i, val) {							  
					 if (val.effect != '') {
						switch (val.effect) {
							case 'slideUp' :
								 $(val.path).slideUp(300);
							break;
							case 'fadeOut' : 
								$(val.path).fadeOut(300);
							break;
							default:
								$(val.path).hide();	
							break;
						}	
					 } else {
					 	$(val.path).hide();
					 }
				});
			break;
			
			case 'siteLoadErrors' :
				var siteErrors = '';
				$.each (msg[operation], function (i, val) {							  
					 siteErrors += ('<span style="color:red">Error ' + (i + 1) +'</span>: ' + val + '\n');
				});
				jAlert(siteErrors,'System errors');
			break;
			
			case 'insertValue' :
				$.each (msg[operation], function (i, val) {							  
					 if (val.type == 'input') $(val.path).val(val.value);
					 else if(val.type == 'text') $(val.path).text(val.value);
					 else if(val.type == 'html') $(val.path).html(val.value);
				});
			break;
			
			case 'insertImg' :
				var img;
				img = document.createElement("img");
				$.each (msg[operation], function (i, val) {							  
					img.src = val.src + val.value;
					img.alt = val.alt;
					img.className = val.className;
					if (val.width != '') img.width = val.width;
					if (val.height != '') img.height = val.height;
					if (val.clear == true) $(val.path).html('');
					$(val.path).append(img);
				});			
			break;
			
			case 'removeElement' :
				$.each (msg[operation], function (i, val) {	
					 if (val.effect != '') {
						switch (val.effect) {
							case 'slideUp' :
								 $(val.path).slideUp(300, function(){$(this).remove()});
							break;
							case 'fadeOut' : 
								$(val.path).fadeOut(300, function(){$(this).remove()});
							break;
							default:
								$(val.path).remove();	
							break;
						}	
					 } else {
					 	$(val.path).remove();
					 }
				});			
			break;
			
			case 'showMessage' :
				$.each (msg[operation], function (i, val) {	
					jAlert(val.value, 'Message');
				});
			break;
			
			case 'refreshScreen' :
				$.each (msg[operation], function (i, val) {	
					jAlert(val.message + ' . Page will be refreshed after ' + val.refTime + ' second');
					setTimeout('( \'val.location\' == "") ? location.reload() : location.href=\''  + val.location + '\' ', (val.refTime * 1000));
				});		
			break;
			
			case 'setAttribute' : 
				$.each (msg[operation], function (i, val) {							  
					 $(val.path).attr(val.name,val.value);
				});				
			break;
			
			case 'removeAttribute' : 
				$.each (msg[operation], function (i, val) {							  
					 $(val.path).removeAttr(val.name);
				});				
			break;
			
			case 'showFormErrors' :
				$('.errors').remove();
				$.each (msg[operation], function (i, val) {	
					$.each (val, function (type, values) {	
						if (type == 'remove') {
							$.each (values, function (j, element) {
								$(element + ' + .errors').remove();
							});
						} else if (type == 'show') {
							$.each (values, function (path, textArray) {
								ul = document.createElement("ul");
								ul.className = 'errors';
								$.each (textArray, function (li, text) {
									liElement = document.createElement("li");
									liElement.appendChild(document.createTextNode(text));
									ul.appendChild(liElement);
								});		
								$(path).after(ul);
							});					
						}
					});
				});
			break;
			
			case 'insertSelectValues':
				$.each (msg[operation], function (i, val) {	
				 var app = '';
					 $.each(val.data, function (key, value){
						app = app + '<option value="'+key+'">'  + value  +'</option>';
					 });
				   $(val.path).append(app);
				   if (val.choose != false) $(val.path).val(val.choose);
				});	
			break;
			
			case 'updateTree' :
				$.each (msg[operation], function (i, val) {	
					menu_elements.exRefresh(val.data, val.ctg);
				});
			break;
			
			case 'refreshTree' :
					menu_elements.refresh();
			break;
			
			case 'updateExGrid' :
				//exGrid[0].grid.addData();
				$.each (msg[operation], function (i, val) {							  
					// $(val.path).attr(val.name,val.value);
					 exGrid[0].grid.addData(val.data);
				});	
			break;
			
			case 'refreshExGrid' :
				$.each (msg[operation], function (i, val) {							  
					$(val.path).flexReload();
				});	
			break;
			
			case 'evalJS' :
				$.each (msg[operation], function (i, val) {							  
					eval(val.data);
				});	
			break;	
		}
	});
}

// Очистка элементов формы
$.fn.clearForm = function() {
  return this.each(function() {
    if (this.tagName.toLowerCase() == "form") {
      return $(":input",this).clearForm();
    }
    switch (this.type) {
      case "password":
      case "textarea":
	  case "hidden":
      case "text":
        this.value = "";
        break;
      case "select-multiple":
      case "select-one":
        this.selectedIndex = 0;
        break;
      case "radio":
      case "checkbox":
        this.checked = false;
        break;
    }
  });
};

$.postJSON = function(url, data, callback) {
	$.post(url, data, callback, "json");
};

function createOverlay() {
	exOverlay = document.createElement("div");
	exOverlay.id = 'exDialogOverlay';
	exOverlay.style.width = '100%';
	exOverlay.style.height = $(document).height() + 'px';
	document.body.appendChild(exOverlay);
	$(exOverlay).fadeIn(200);
}

// Returns true if variable is an object  
function is_object( mixed_var ) {
    if(mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}


function enable_smooth_scroll() {
    function filterPath(string) {
        return string
                .replace(/^\//,'')
                .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
                .replace(/\/$/,'');
    }

    var locationPath = filterPath(location.pathname);
    
    var scrollElement = 'html, body';
    $('html, body').each(function () {
        var initScrollTop = $(this).attr('scrollTop');
        $(this).attr('scrollTop', initScrollTop + 1);
        if ($(this).attr('scrollTop') == initScrollTop + 1) {
            scrollElement = this.nodeName.toLowerCase();
            $(this).attr('scrollTop', initScrollTop);
            return false;
        }    
    });
    
    $('a[href*=#]').each(function() {
        var thisPath = filterPath(this.pathname) || locationPath;
        if  (   locationPath == thisPath
                && (location.hostname == this.hostname || !this.hostname)
                && this.hash.replace(/#/, '')
            ) {
                if ($(this.hash).length) {
                    $(this).click(function(event) {
                        var targetOffset = $(this.hash).offset().top;
                        var target = this.hash;
                        event.preventDefault();
                        $(scrollElement).animate(
                            {scrollTop: targetOffset},
                            400,
                            function() {
                                location.hash = target;
                        });
                    });
                }
        }
    });
}
//-->