//funkcia na ziskanie URL routera
var Router = function (route,params) {
    //parametre
    if (typeof(params) == 'object') {
        var p = '';
        $.each(params,function (name,value) {
            if (p != '') {
                p += '&';
            }
            p += escape(name)+'='+escape(value);
        });
        return Router(route)+'?'+p;
    }
    else {
        return registry.webroot + '/' + route;
    }
};
Router.route = function (route,params) {
    location.href = Router(route,params);
}

function Registry() {
    this.webroot = '';
    this.themePath = this.webroot + 'public/themes';
    this.currentUser = {
    UID: 1,
    displayName: 'Letenky.sk'
    };
}

var registry = new Registry;


function __(msg) {
    return msg;
}

function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}

function loadScript(src) {
    var head = document.getElementsByTagName('head').item(0);
    var newScript = document.createElement('script');
        newScript.src = src;
        newScript.type = 'text/javascript';
    head.appendChild(newScript);
}

function toggleSubmenu(e) {
    var submenu = e.parentNode.parentNode.getElementsByTagName('ul').item(0);
    if (submenu) {
        submenu.style.display = submenu.style.display == 'none' ? 'block' : 'none';
    }
}

var timer = null;
var IMG = null;
var NewWindow = null;
function ViewImage(Isrc,title) {
	IMG = new Image;
	IMG.src = Isrc;
	if (typeof(title)=="undefined" || title=="") title="Gallery";
	if (NewWindow) { NewWindow.close(); }
	if (NewWindow==null || NewWindow.closed) {
		settings=
		 "left="+50+","
		 +"top="+50+","
		 +"width="+640+","
		 +"height="+480+","
		 +"toolbar=no,"
		 +"location=no,"
		 +"directories=no,"
		 +"status=no,"
		 +"menubar=no,"
		 +"scrollbars=yes,"
		 +"resizable=yes"
		 NewWindow = window.open("",'Gallery',settings);
	}
	NewWindow.document.open();
	//NewWindow.document.clear();
	NewWindow.document.write(
         "<html><head><title>"+ title +"</title>"
        +"</head>\n"
        +"<body style=\"text-align:left;margin:15px;\">\n"
        +"<img onclick=\"window.close();\" src=\"" + IMG.src + "\" border=\"0\" alt=\""+title+"\" />\n"
        +"</body>\n"
        +"</html>"
	);
	NewWindow.document.close();
	NewWindow.focus();
	timer = setInterval("resize()",250);
}

function resize(plusW,plusH) {
    if(!IMG.complete){ return; }
    clearInterval(timer);
    var windowW = IMG.width+(plusW ? plusW : 50);
    var windowH = IMG.height+(plusH ? plusH : 60);
    if (windowW >= screen.width - 100)
    {
        windowW = screen.width - 100;
    }
    if (windowH >= screen.height - 100)
    {
        windowH = screen.height - 100;
    }
	resizeWindowTo(NewWindow,windowW,windowH);
	IMG = null;
    clearInterval(timer);
}

function resizeWindowTo(WindowObject,w,h) {
	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			WindowObject.outerWidth=w;
			WindowObject.outerHeight=h;
		}
		else WindowObject.resizeTo(w,h);
	}
}

//otvaranie dokumentov v okne
function Proceed_okno_anchors() {
    var aa = document.getElementsByTagName('A');
    for (var a = 0 ; a < aa.length ; a++) {
        if (aa[a].className.indexOf('okno') != -1) {
            aa[a].onclick = function () {
                var w = screen.width - 80;
                var h = screen.height - 220;
                var settings =
                     "left="+Math.round((screen.width - w) / 2)+","
                    +"top=47,"
                    +"width="+w+","
                    +"height="+h+","
                    +"toolbar=yes,"
                    +"location=yes,"
                    +"directories=no,"
                    +"status=no,"
                    +"menubar=no,"
                    +"scrollbars=yes,"
                    +"resizable=yes";
                var NewWindow = window.open(this.href,'Document',settings);
                NewWindow.focus();
                return false;
            }
        }
    }
}
addEvent(window,'load',Proceed_okno_anchors);

function KontaktyDisplayPart(pid) {
    KontaktyHideParts(pid);
    document.getElementById(pid).style.display = 'block';
}

function KontaktyHideParts(exclude) {
    var tbls = document.getElementsByTagName('DIV');
    for (var i = 0 ; i < tbls.length ; i++) {
        if (tbls[i].className.indexOf('kontaktyHide') != -1) {
            if (tbls[i].id != exclude) {
                tbls[i].style.display = 'none';
            }
        }
    }
}
addEvent(window,'load',KontaktyHideParts);

function CalendarArrival() {
    var prefix = 'navrat';
    var den = document.getElementById(prefix + '_den').value;
    var mesiac = document.getElementById(prefix + '_mesiac').value;
    var rok = document.getElementById(prefix + '_rok').value;
    ShowPage('/files/calendar/calendar.php?D=' + den + '&M=' + mesiac + '&Y=' + rok + '&jsid=d&day=' + prefix + '_den&month=' + prefix + '_mesiac&year=' + prefix + '_rok',220,210,'addin_calendar');
}

function CalendarDeparture() {
    var prefix = 'odlet';
    var den = document.getElementById(prefix + '_den').value;
    var mesiac = document.getElementById(prefix + '_mesiac').value;
    var rok = document.getElementById(prefix + '_rok').value;
    ShowPage('/files/calendar/calendar.php?D=' + den + '&M=' + mesiac + '&Y=' + rok + '&jsid=d&day=' + prefix + '_den&month=' + prefix + '_mesiac&year=' + prefix + '_rok&all=1',220,210,'addin_calendar');
}

function Calendar(prefix) {
    var den = document.getElementById(prefix + '_den').value;
    var mesiac = document.getElementById(prefix + '_mesiac').value;
    var rok = document.getElementById(prefix + '_rok').value;
    ShowPage('/files/calendar/calendar.php?D=' + den + '&M=' + mesiac + '&Y=' + rok + '&jsid=d&day=' + prefix + '_den&month=' + prefix + '_mesiac&year=' + prefix + '_rok',220,210,'addin_calendar');
}

function ShowDestinations(element, where, from) {
    if (from && from != '-') {
        var dest_from = from;
        AjaxRequest.get(
            {
                'url': '/files/destinations/destinations.php?where=' + where + '&from=' + dest_from,
                'onSuccess':function(req) {
                    DisplayDestinations(req,element);
                },
                'onError':function(req) { }
            }
        );
    }
    else {
        AjaxRequest.get(
            {
                'url': '/files/destinations/destinations.php?where=' + where,
                'onSuccess':function(req) {
                    DisplayDestinations(req,element);
                },
                'onError':function(req) { }
            }
        );
    }
}

function ShowDestinationsSelect(destination) {
    AjaxRequest.get(
        {
            'url': '/files/destinations/destinations_select.php?from=' + destination,
            'onSuccess': function (req) {
                var select = document.getElementById('destination_from');
                select.innerHTML = req.responseText;
            },
            'onError': function (req) { }
        }
    );
}

function DisplayDestinations(req,element) {
    if (element != undefined) {
        element.style.display = 'block';
        element.style.position = 'absolute';
        element.style.width = '400px';
        element.style.height = '400px';
        element.style.border = '2px solid #CCC';
        element.style.background = '#FFF';
        element.innerHTML = req.responseText;
    }
}

function ShowAirlines(element) {
    AjaxRequest.get(
        {
            'url': '/files/airlines/airlines.php',
            'onSuccess':function(req) {
                DisplayDestinations(req,element);
            },
            'onError':function(req) { }
        }
    );
}

NewWindow3 = null;
function ShowPage(href, w, h) {
	if(NewWindow3){ NewWindow3.close(); }
	if(NewWindow3==null || NewWindow3.closed){
		var top = screen.height/2 - h/2;
		var left = screen.width/2 - w/2;
		var settings =
	 		"left=" + left + "px,"
			+"top=" + top + "px,"
			+"width=" + w + "px,"
			+"height=" + h + "px,"
			+"toolbar=no,"
			+"location=no,"
			+"directories=no,"
			+"status=no,"
			+"menubar=no,"
			+"scrollbars=yes,"
			+"resizable=yes";
		NewWindow3 = window.open(href,'okno',settings);
	}
	NewWindow3.focus();
}

function ValidateBookingForm(form) {
    var okej = true;
    var report = '';
    var customer = document.getElementById('customer0').value;
    var email = form.email.value;
    var time_best_den = form.time_best_den.value;
    var time_best_mesiac = form.time_best_mesiac.value;
    var time_best_rok = form.time_best_rok.value;
    var back_best_den = form.back_best_den.value;
    var back_best_mesiac = form.back_best_mesiac.value;
    var back_best_rok = form.back_best_rok.value;
    var oneway = form.oneway.checked;
    
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    
    if (!customer) {
        okej = false;
        report += 'Musíte zadať meno cestujúceho\n';
    }
    if (!email) {
        okej = false;
        report += 'Musíte zatať emailovú adresu\n';
    }
    else {
        if (!filter.test(email)) {
            okej = false;
            report += 'Nekorektná emailová adresa\n';
        }
    }
    if (!time_best_den || !time_best_mesiac || !time_best_rok) {
        okej = false;
        report += 'Musíte zadať dátum odchodu\n';
    }
    if (!oneway && (!back_best_den || !back_best_mesiac || !back_best_rok)) {
        okej = false;
        report += 'Musíte zadať dátum návratu\n';
    }
    if (okej == true) {
        form.submit();
    }
    else {
        alert(report);
    }
}

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

/*
    ==========================
    ERROR HLASKY
    ==========================
*/
$(function() {
    var buttons = {};
    buttons[__('Zatvoriť')] = function() { 
        $(this).dialog("close");
    };
    var e = $("div.report");
    if(e.length > 0){
        var tmp = '';
        e.each(function(){
            tmp += $(this).html() + "<br />";
            $(this).remove();
        });
        $("<div />").addClass('report').html(tmp).appendTo('body').dialog({
            bgiframe: true,
            autoOpen: true,
            modal: true,
            resizable: false,
            draggable: false,
            width: 400,
            title: "Upozornenie",
            buttons: buttons
        });
    }
});

jQuery(function($){
    if (typeof($.datepicker) != 'undefined') {    
        $.datepicker.regional['sk'] = {
            clearText: 'Zmazať', clearStatus: '',
            closeText: 'Zavrieť', closeStatus: '',
            prevText: '',  prevStatus: '',
            prevBigText: '', prevBigStatus: '',
            nextText: '', nextStatus: '',
            nextBigText: '', nextBigStatus: '',
            currentText: 'Dnes', currentStatus: '',
            monthNames: ['Január','Február','Marec','Apríl','Máj','Jún',
            'Júl','August','September','Október','November','December'],
            monthNamesShort: ['Jan','Feb','Mar','Apr','Máj','Jún',
            'Júl','Aug','Sep','Okt','Nov','Dec'],
            monthStatus: '', yearStatus: '',
            weekHeader: 'Ty', weekStatus: '',
            dayNames: ['Nedel\'a','Pondelok','Utorok','Streda','Štvrtok','Piatok','Sobota'],
            dayNamesShort: ['Ned','Pon','Uto','Str','Štv','Pia','Sob'],
            dayNamesMin: ['Ne','Po','Ut','St','Št','Pia','So'],
            dayStatus: 'DD', dateStatus: 'D, M d',
            dateFormat: 'dd.mm.yy', firstDay: 0, 
            initStatus: '', isRTL: false
        };
        $.datepicker.setDefaults($.datepicker.regional['sk']);
    }
});

function createDate(string) {
    var year = Number(string.substring(0, 4));
    var month = Number(string.substring(5, 7));
    var day = Number(string.substring(8, 10));
    return new Date(year, month - 1, day);
}

function trim(str, chars) {
    str = str || '';
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


$(function(){
    if(document.getElementById('bannerA') != null){
        var so1 = new SWFObject($('#bannerA').attr('rel'), 'Banner A', 120, 480, '7.0');
        so1.addParam("quality", "high");
        so1.addParam("wmode", "transparent");
        so1.write('bannerA');
    }
        
    if(document.getElementById('bannerB') != null){
        var so1 = new SWFObject($('#bannerB').attr('rel'), 'Banner B', 120, 480, '7.0');
        so1.addParam("quality", "high");
        so1.addParam("wmode", "transparent");
        so1.write('bannerB');
    }

    if(document.getElementById('bannerC') != null){
        var so1 = new SWFObject($('#bannerC').attr('rel'), 'Banner C', 120, 480, '7.0');
        so1.addParam("quality", "high");
        so1.addParam("wmode", "transparent");
        so1.write('bannerC');
    }
});
