if (window.console == undefined) { window.console = {log:function(){}, info: function(){}, warn: function(){}}; } // firebug-ie-fix
window.__sessionSaverInterval = null;
$(function(){
    $('#ajaxProgress').ajaxSend(function(a,b) { $('#ajaxProgress').show()});
    $('#ajaxProgress').ajaxComplete(function(a,b) {
		$('#ajaxProgress').hide();
		window.setTimeout(doAjaxOnload,500);
		if (document.getElementById('doLogout') && window.__sessionSaverInterval) {
			window.clearInterval(window.__sessionSaverInterval);
			window.__sessionSaverInterval = window.setInterval(sessionSaver,300000); // 5 minutes
		}
	});
    window.onbeforeunload = function() { $.event.trigger('ajaxSend') }
    if (document.getElementById('doLogout')) {
        window.__sessionSaverInterval = window.setInterval(sessionSaver,300000); // 5 minutes
    }
    $('div#state_townfrom select').change(function(){
		var curselect = $(this);
        $.get('/helpers/changestateandtownfrom.php?var=' + $(this).attr('id') +'&val=' + $(this).val() + '&page_id=' + $('div#state_townfrom').attr('current_page'),function(data){
            if (data != '0') {
                if (data == '1') {
					var thref = window.location.href;
					if (thref.indexOf('/ac_')!=-1) thref = thref.slice(0,thref.indexOf('/ac_'));
					if (curselect.attr('othuri')!==undefined) thref = curselect.attr('othuri');
					window.location.href = thref;
                    //window.location.replace(thref);
                } else {
                   window.location.replace(data);
                }
            }
        })
    });
$.datePicker.setLanguageStrings(
	['Воскресенье','Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
	['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
	{p:'Назад', n:'Вперёд', c:'Закрыть', b:'Выберите дату'}
);
    $.datePicker.setDateFormat('dmy','.');
    $('input.date').datePicker();
});



function doAjaxOnload() {
   $('input.date').datePicker();
   colorizeTable();
   initSTable();
   if (typeof TB_init == 'function') {
       TB_init();
   }
   previewInit();
}
function sessionSaver() {
    $.get('/helpers/session.php',function(data){
        if (data == '0') {
            window.location.reload();
        }
    })
}


function colorizeTable() {
//    $("table.std:not(.fltr) tr:nth-child(even)").addClass("even");
    $("table.std tr:nth-child(even)").each(function() {
		if ($(this).attr('njs')==undefined) {
			$(this).addClass("even");
		}
	});
    $("table.std td.red").attr('title','остановка продаж в гостинице');
    $("table.std td.green").attr('title','мгновенное подтверждение');

}

function addOnLoadEvent() {
	var root = window.addEventListener || window.attachEvent ? window : document.addEventListener ? document : null;
	if (root) {
		for (var i = 0; i < arguments.length; i++) {
			if ('function'  == typeof(arguments[i]))
				addHandler(root,'load',arguments[i]);
		}
	}
}

    var doLogoutFunction = function(){
        msg = 'Покинуть систему? Благодарим за использование нашей системы! Pegas Touristik.';
        if (confirm(msg)) {
            window.location.href = '/helpers/logout.php';
        }
    }
function addHandler(object, event, handler) {
  if (typeof (object.addEventListener) != 'undefined')
    object.addEventListener(event, handler, false);
  else if (typeof (object.attachEvent) != 'undefined')
    object.attachEvent('on' + event, handler);
  else {
    var handlersProp = '_handlerStack_' + event;
    var eventProp = 'on' + event;
    if (typeof (object[handlersProp]) == 'undefined') {
      object[handlersProp] = [];
      if (typeof (object[eventProp]) != 'undefined')
        object[handlersProp].push(object[eventProp]);
      object[eventProp] = function(e) {
        var ret = true;
        for (var i = 0; ret != false && i < object[handlersProp].length; i++)
          ret = object[handlersProp][i](e);
        return ret;
      }
    }
    object[handlersProp].push(handler);
  }
}
var __cached_fake_focus = null;
function fakeFocus() {
    if (arguments.length == 1) {
      var obj = document.getElementById('fake_' + arguments[0]);
    }
    if (!obj) {
        var obj = __cached_fake_focus || document.getElementById('top_fake_focus');
    }
    if (obj)
        obj.focus();
}
function saveProfile(data) {
    $.post('/helpers/profile.php',data);
}
addOnLoadEvent(doAjaxOnload);

function initSTable() {
    return;
	$("table.fltr:not(.srtbl) ").tableSorter({
        sortClassAsc: 'sortUp', // class name for asc sorting action
        sortClassDesc: 'sortDown', // class name for desc sorting action
        highlightClass: 'highlight', // class name for sort column highlighting.
        stripingRowClass: ['odd','even'],
        stripRowsOnStartUp: true,
        disableHeader: ['Даты действия','Гостиницы','Категория','Примечание','Остановки продаж','Вылеты','Транспорт','&nbsp;', 'Э', 'Б','Н','П'],
        headerClass: 'largeHeaders', // class name for headers (th's)
        dateFormat: 'dd.mm.yyyy' //yyyy-mm-dd' // set date format for non iso dates default us, in this case override and set uk-format
    });
}

function jquery_openWindow(variables, method, target, action) {
	if (variables!==undefined) {
		if (method===undefined) method='get';
		if (target===undefined) target='_blank';
		if (action===undefined) action='';
		var form_oW = document.getElementById('form_oW');
		var text = '';
		if (form_oW != null) $('#form_oW').remove();
		text = '<form style="display:none;" id="form_oW" method="'+method+'" '+((target.length>0)?'target="'+target+'" ':'')+' '+((action.length>0)?'action="'+action+'" ':'')+'>';
		$.each(variables, function(i,n) {
			text += '<input type="hidden" name="'+i+'" value="'+n+'">';
		});
		text += '</form>';
		$(document.body).append(text);
		$('#form_oW').submit();
	}
}