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

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);
        title = self.attr('title');
        self.removeAttr('title');
        self.data('title', title);
        if (self.is(':text') || self.is(':password')) {
            if (self.is(':password')) {
                var tmp = $('<input type="text"/>').val(title).addClass(self.attr('class')).attr('name', 'password_hint').data('title', 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.data('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.data('title') || inpt.val() == '') {
        inpt.addClass('hint').val(inpt.data('title'));
    }
}
jQuery.inputHintHide = function (inpt) {
    inpt = jQuery(inpt);
    inpt.removeClass('hint');
    if (inpt.val() == inpt.data('title')) {
        inpt.val('');
    }
}

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

$(function(){
    $('.mainMenu .menu li').hover(function(){
        $(this).addClass('hover');
        $('ul',this).fadeIn('fast');
    }, function(){
        $(this).removeClass('hover');
        $('ul',this).fadeOut('fast');
    })
    
    $('.mainMenu .menu li ul li').hover(function () {$(this).addClass('active')}, function () {$(this).removeClass('active')})
        
    // 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();
	});
	$('#lostPasswd').click(function(){
        $('#lostPasswdFormDialog').dialog('open');
        $(':text:first', $('#lostPasswdFormDialog')).focus();
	});
    $('#loginForm, #lostPasswdForm').submit(function(){
        $(this).hide();
        $(this).parent().addClass('dialogLoading');
        return true;
    });
    
    makeTooltips('img');
});

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');})
}

function ajaxOverlay(kill, preloader) {
    if (typeof kill == 'undefined') {
        kill = false;    
    }
    if (typeof preloader == 'undefined') {
        preloader = true;    
    }
    if (kill) {
        $('div.preloader').remove();
        $('div.ui-widget-overlay').remove();
        return true;
    }
    $('div.preloader').remove();
    $('div.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> ' + msgs[i] + '</div>';    
    }
    var body = $('<div class="errorMsg ui-state-error ui-corner-all"></div>');
    body.html(msg);
    closeBtn = $('<span class="ui-icon ui-icon-circle-close ico_cancel"></span>').click(function () {
        $('.errDialog').html('').remove();
        ajaxOverlay(true);
    });
    body.prepend(closeBtn);
    var tag = $('<div class="errDialog ui-widget"><div class="ui-widget-shadow"></div><div class="errorContent"></div>');
    body.appendTo($('.errorContent', tag));
    tag.appendTo('body');
    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;

function showProgress(type) {
    if (typeof type == 'undefined') {
        return false;   
    }
    ajaxOverlay(false, false);
    currentKrok = $('#krok_' + type);
    currentKrok.show();
    var body = $('.medzikrok-content-body', currentKrok);
    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);
    setTimeout('updateProgressbar(' + step + ');', 1000);
}

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

function parseResponse(res) {
    if (/^\{/.test(res)) {eval('var 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
    });
}
