/* AJAX ERROR */
//$(document).ajaxError(function (request,settings,e) {
//    alert('Error requesting URL: '+e.url);
//});

var bwIE60 = (navigator.appVersion.indexOf("MSIE 6.0") != -1) ? "True" : "False";
var bwIE70 = (navigator.appVersion.indexOf("MSIE 7.0") != -1) ? "True" : "False";

if (typeof SKINROOT == 'undefined') {
    var SKINROOT = WEBROOT;    
}
function __(msg) {
    if (typeof locale != 'undefined' && typeof locale['msg'] != 'undefined') {
        return locale['msg'];
    } else {
        return msg;    
    }
}

/* URL ROUTER */
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 {
        if (/^http/i.test(route)) {
            return route;    
        } else {
            return '/' + route;
        }
    }
};
Router.route = function (route,params) {
    location.href = Router(route,params);
}

/* Plugin na input hint */
jQuery.fn.inputHint = function () {
    this.each(function () {
        var self = $(this);
        if (self.is(':text') || self.is(':password')) {
            if (self.is(':password')) {
                var tmp = $('<input type="text"/>').val(self.attr('title')).addClass(self.attr('class')).removeClass('hint').attr('name', 'password_hint').attr('title', self.attr('title')).insertAfter(self);
                tmp.focus(function(){
                    tmp.hide();
                    self.show().focus();
                });
            }
            jQuery.inputHintShow(self);
            self.focus(function () {
                jQuery.inputHintHide(this);
            }).blur(function () {
                jQuery.inputHintShow(this);
            }).change(function () {
                jQuery.inputHintShow(this);
            }).parents('form').submit(function () {
                jQuery.inputHintHide(self);
                return true;
            });
        }
    });
    return this;
};
jQuery.inputHintShow = function (inpt) {
    inpt = jQuery(inpt);
    if (inpt.is(':password')) {
        if (inpt.val() == inpt.attr('title') || inpt.val() == '') {
            inpt.siblings(':text[name=password_hint]').show();
            inpt.hide();
        } else {
            inpt.siblings(':text[name=password_hint]').hide();
            inpt.show();
        }
    } else if (inpt.val() == inpt.attr('title') || inpt.val() == '') {
        inpt.addClass('hint').val(inpt.attr('title'));
    }
}
jQuery.inputHintHide = function (inpt) {
    inpt = jQuery(inpt);
    inpt.removeClass('hint');
    if (inpt.val() == inpt.attr('title')) {
        inpt.val('');
    }
}


function unique() {
    var d = new Date();
    return d.getTime();
}

function count(obj) {
    var len = 0;
    for (var k in obj) {if (typeof obj[k] != 'function') {len++};}
    return len;
}

$(function(){
    $('.menu li').hover(function() {
        $(this).addClass('hover');
        $('ul',this).show();
    }, function() {
        $(this).removeClass('hover');
        $('ul',this).hide();
    })
    
    /* $('.menu li ul li').hover(function () {
        $(this).addClass('active');
    }, function () {
        $(this).removeClass('active');
    }); */
    
    var item_count = 0;
    var items_width = 0;
    var last_item_width = 0;
	$('#content .menu li:not(.submenu)').each(function (idx, el) {
		$(el).mouseenter(function () {
			$('ul:first', this).show();
			var offset = $('a:first', this)[0].offsetLeft;
			var width = $('ul:first', this)[0].offsetWidth;
			if (bwIE60 == "True" || bwIE70 == "True") {
				offset = this.offsetLeft;
			}
			offset -= 13;
			if (offset + width > 960) {
				var diff = 960 - (offset + width);
				offset = offset + diff;
			}
			$('ul:first', this).css('left', offset + 'px');
		});
		$(el).mouseleave(function () {
			$('ul:first', this).hide();
		});
		
		item_count++;
		last_item_width = $(el).outerWidth();
		items_width += last_item_width;
	});
	var last_item_width_add = 960 - items_width;
	var current_last_item_width = $('#content .menu li:not(.submenu):last').width();
	$('#content .menu li:not(.submenu):last').css('width', parseInt(current_last_item_width, 10) + parseInt(last_item_width_add, 10) + 'px');
    
    // nastavime buttony
    createButtons();
    //hinty vo formularoch
	$('input.hint').inputHint();
	
	// login dialog
	$('#loginFormDialog').dialog({
        title: $('#loginFormDialog').attr('title'),
        autoOpen: false,
        modal: true,
        width: 400
	});
	$('#lostPasswdFormDialog').dialog({
        title: $('#lostPasswdFormDialog').attr('title'),
        autoOpen: false,
        modal: true,
        width: 400
	});
	$('#login').click(function(){
        $('#loginFormDialog').dialog('open');
        $(':text:first', $('#loginFormDialog')).focus();
        return false;
	});
	$('#lostPasswd').click(function(){
        $('#lostPasswdFormDialog').dialog('open');
        $(':text:first', $('#lostPasswdFormDialog')).focus();
	});
    $('#loginForm, #lostPasswdForm').submit(function(){
        $(this).hide();
        $(this).parent().addClass('dialogLoading');
        return true;
    });
    makeTooltips('img');
    
    // formulare v taboch na lavej strane
    $('#searchforms a').click(function () {
        var to_show = $(this).attr('rel');
        $('.left_form_content').hide();
        $('#left_form_' + to_show).show();
        
        // datepickery a selectBoxy
        /* $('#topDest, #stars').selectBox(); */
        
        $('#searchforms a').each(function () {
            var item_class = $(this).attr('rel');
            if (!$(this).parent().is('.' + item_class + '_inactive')) {
                $(this).parent().addClass(item_class + '_inactive');
            }
        });
        
        $('#searchforms li.' + to_show).removeClass(to_show + '_inactive');
    });
});

function createButtons(tag) {
    if (typeof tag != 'object') {
        var tag = $('body');     
    }
    $('.ui-button', tag).each(function(){
        $(this).addClass('ui-widget ui-corner-all');
        if (!$(this).hasClass('ui-state-highlight')) {
            $(this).addClass('ui-widget ui-corner-all ui-state-default');
        }
    });
    $('.ui-button', tag).hover(function(){$(this).addClass('ui-state-hover');}, function(){$(this).removeClass('ui-state-hover');})
}
var overlayIndex;
function ajaxOverlay(kill, preloader) {
    if (typeof kill == 'undefined') {
        kill = false;    
    }
    if (typeof preloader == 'undefined') {
        preloader = true;    
    }
    if (kill) {
        $('div.preloader').remove();
        if (overlayIndex) {
            $('div.ui-widget-overlay').css('z-index', overlayIndex);
        } else {
            $('div.ui-widget-overlay').remove();    
        }
        return true;
    }
    if ($('.ui-widget-overlay').length) {
        overlayIndex = $('.ui-widget-overlay').css('z-index');   
    } else {
        overlayIndex = null;
    }
    $('div.preloader').remove();
    $('.ui-widget-overlay').remove();
    $('html, body').animate({scrollTop:0}, 0);
    var overlay = $('<div />').addClass('ui-widget-overlay').css('z-index', 9998).css('height', Math.max($(document).height(), $(window).height()));
    var left = ($('.body').width() / 2) - 130;
    if (preloader) {
        var preloader = $('<div />').addClass('preloader').css('left', left + 'px');
        preloader.append('<img src="' + SKINROOT + '/images/ajax-progress.gif" />')
        $('.body').append(preloader);
    }
    $('body').append(overlay);
}

function alertDialog(msgs) {
    var msg = '';
    for(i in msgs) {
        msg += '<div><span class="ui-icon ui-icon-alert" style="float:left;"></span><p style="margin: 0 25px">' + msgs[i] + '</p></div>';    
    }
    var body = $('<div class="errorMsg ui-state-error ui-corner-all"></div>');
    body.html(msg);
    closeIco = $('<span class="ui-icon ui-icon-circle-close ico_cancel"></span>').click(function () {
        $('.errDialog').html('').remove();
        ajaxOverlay(true);
    });
    buttons = $('<div class="buttons" style="text-align:right;"></div>');
    closeBtn = $('<span class="ui-button">Zatvoriť</span>').click(function () {
        $('.errDialog').html('').remove();
        ajaxOverlay(true);
    });
    buttons.append(closeBtn); 
    body.prepend(closeIco);
    body.append(buttons);
    var tag = $('<div class="errDialog ui-widget"><div class="ui-widget-shadow"></div><div class="errorContent"></div>');
    body.appendTo($('.errorContent', tag));
    tag.appendTo('body');
    createButtons(tag);
    tag.show();
    $('.ui-widget-shadow', tag).css({width: body.width()+20, height: body.height() + 20});
    tag.css('left', (($(window).width() / 2) - body.width() /2));
    ajaxOverlay();
}

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 formSubmit(id) {
    $('form#' + id).submit();
}

function debug(msg) {
    if (typeof console != 'undefined') {
        window.console.log(msg);    
    }
}

var currentKrok;
var currentKrokTimeout;

function showProgress(type) {
    if (typeof type == 'undefined') {
        return false;   
    }
    ajaxOverlay(false, false);
    currentKrok = $('#krok_' + type);
    currentKrok.show();
    var body = $('.medzikrok-content-body', currentKrok);
    body.addClass('ui-widget-content ui-corner-all');
    var left = ($(document).width() / 2) - body.width() /2;
    currentKrok.css('left', left).css('z-index', 9999);
    //$('.ui-widget-shadow', currentKrok).css({width: body.width()+20, height: body.height()+45});
    $('.progressBar', currentKrok).progressbar();
    $('.progressBar', currentKrok).progressbar('value', 0);
    var step = Number(currentKrok.attr('rel')) > 0 ? (100 / Number(currentKrok.attr('rel'))) : (100/60);
    currentKrokTimeout = setTimeout('updateProgressbar(' + step + ');', 1000);
}

function updateProgressbar(step) {
    current = $('.progressBar', currentKrok).progressbar('value');
    $('.progressBar', currentKrok).progressbar('value', current + step);
    $('.closeStep', currentKrok).click(function () {
        currentKrok.hide();
        ajaxOverlay(true);
        $(this).hide();
    });
    if (current < 100) {
        currentKrokTimeout = setTimeout('updateProgressbar(' + step + ')', 1000);
    } else {
        $('.closeStep', currentKrok).show();
    }
}

function parseResponse(res) {
    if (/^\{/.test(res)) {eval('res = '+res+';');}
    return res;
}

function makeTooltips(elem, parent) {
    var elems;
    if (typeof(parent) == 'undefined') {
        elems = $('.clickable[title]'+(elem ? ', '+elem+'[title]' : ''));
    } else {
        elems = $('.clickable[title]'+(elem ? ', '+elem+'[title]' : ''),parent);
    }
    elems.tooltip({
        delay: 0,
        track: true,
        fade: 250,
        showURL: false
    });
}

