var global_ajaxCache = false;

function Clone() { };
function clone(obj) {
    Clone.prototype = obj;
    return new Clone();
}
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// trik ako docielit zavolanie eventu pri dokonceni - napr window.resize, fire event az ked doresizujes !!
var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();


Number.prototype.formatMoney = function(decPlaces, decSeparator, thouSeparator, currencySymbol, separator) {
    // check the args and supply defaults:
    separator = separator == undefined ? '&nbsp;' : separator;
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
    decSeparator = decSeparator == undefined ? "," : (decSeparator == ' ' ? separator : decSeparator);
    thouSeparator = thouSeparator == undefined ? " " : (thouSeparator == ' ' ? separator : thouSeparator);
    currencySymbol = currencySymbol == undefined ? "€" : currencySymbol;

    var n = this,
        sign = n < 0 ? "-" : separator,
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;

    return (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "") + sign + currencySymbol;
};

String.prototype.sklonovatko = function(num,singular,plural1,plural2) {
    return (parseInt(num) == 1) ? singular : ((parseInt(num) > 2 && parseInt(num) < 5) ? plural1 : plural2);
};

function getReady() {
  var deferredReady = $.Deferred();
  $(document).ready(function() {
    deferredReady.resolve();
  });
  return deferredReady.promise();
}

$(document).ready(function(){
    //iny use-case ako <noscript>, ked potrebujeme nieco zobrazit len do momentu, kym nenabehne DOM
    $('.noscript').hide();

    //IE trick - apply different css to active form elements
    $("input").bind('focus',function() {
        $(this).addClass("active");
    });
    $("input").bind('blur',function() {
        $(this).removeClass("active");
    });

    $("input[tooltip], textarea[tooltip]").bind('focusin',function(){
        
        if($(this).hasClass('datepicker') || $(this).hasClass('datecalendar')){
            var _this = this;
            $(this).closest('.form-group').find('.tool-tip:not(.visible)').slideDown('fast',function(){
                $(_this).datepicker(($(_this).attr('dateparams')) ? JSON.parse($(_this).attr('dateparams')) : {});
                $(_this).datepicker('show');                 
            });
        }
        else{
            $(this).closest('.form-group').find('.tool-tip').slideDown('fast');    
        }        
    });
    
    $("input[tooltip], textarea[tooltip]").bind('focusout',function(){
        if($(this).hasClass('datepicker') || $(this).hasClass('datecalendar')) {}
        else {
            var t = $(this).closest('.form-group').find('.tool-tip:not(.visible)');
            if($(t).hasClass('hidden-once')) {
                $(t).removeClass('hidden-once').addClass('visible').unbind('focusin');
            } else {
                t.delay(800).slideUp('fast');
            }
        }
    });


//    $("input[tooltip], textarea[tooltip]").closest('.form-group').find('.tool-tip').css({'display':'block'});


    $('input.datepicker, .datecalendar').each(function(){                
        if(!$(this).attr('tooltip')){
            var _this = this;
            return $(_this).datepicker(($(_this).attr('dateparams')) ? JSON.parse($(_this).attr('dateparams')) : {})    
        }        
    });

    $('input[type=file]').bootstrapFileInput();
    $('input[type=range]').bootstrapRangeInput();


    $('.multiselect').multiselect({
        numberDisplayed: 2,
        buttonWidth: '100%',
        buttonClass: 'btn btn-default',
        enableFiltering: false
    });
    $('.see-more-btn').click(function(e){
        e.preventDefault();
        $(this).closest('.see-more').find('.see-more-holder').toggleClass('active');
    });


    $('.tp').tooltip({html:true});

    $(".stats ul").rotate();

    $('tr.clickable').each(function(){
        $(this).bind('click',function(event){
            url = $(event.currentTarget).attr('dataurl') || $(event.currentTarget).find('a').attr('href');
            if(typeof(url) != 'undefined' && event.target.tagName != 'INPUT') {
                window.location.href = url;
            }
        });
    });

    suggestAddress.init();
    dependencyBlockInit();
    address.init();
    initCountdown();
	$('[js="iban_calc"]').iban_calc().print();
    highlight_country.init();
    tel_req_period.init();

    
    $('#proces_loan_data').click(function(e){
        e.preventDefault();
        $('#processing_loan_data').popup({
            autoopen: true,
            color: 'white',
            opacity: 1,
            transition: '0.3s',
            scrolllock: true,
            escape:false,
            blur:false
        });
                
        setTimeout(function() {
            $('#frm-form_LoanRequest_step6').submit();
        }, 5000);
        
        return false;
        //alert(1);
    });

    $('.showmore').bind('click',function(event){
        event.preventDefault();
        if($(this).attr('data-toggle')) {
            $(this).closest('.news-box').find('#'+$(this).attr('data-toggle')).toggle(function(showOrHide,el){
                if ( showOrHide === true ) {
                    $(el).slideDown();
                    window.location.hash = $(this).attr('data-toggle');
                } else if ( showOrHide === false ) {
                    $(el).slideUp();
                    window.location.hash = $(this).attr('data-toggle').substr(0,$(this).attr('data-toggle').indexOf('#'));
                }
            });
        }
    });
    

    /****************************   Forum   ***********************************/
    $( ".reply" ).bind('click',function(event) {

       event.preventDefault();

       var id_r = $(this).attr('id-reply-div');
       
       $(".cancelReply").hide();
      
        $('.reply_div').hide();
        $('.reply').show();

        $("#"+id_r).show();

        $("#"+id_r+"XY").show();//cancel reply

        $(this).hide();
        
    });

    $(".cancelReply").bind('click',function(event){

        event.preventDefault();

        var id_c = $(this).attr('id-cancel-div');

        $(".cancelReply").hide();

        $('.'+id_c).hide();
        $('.reply').show();

        $("#"+id_c).hide();



        $(this).hide();
    });

	$(document).on('mouseenter','.profilBoxHover',function(event){
		var url = '/profil/'+$(this).attr('data-name');

		url = url+'?redirect='+ encodeURIComponent(window.location.href);
		
		console.log(url);
		
		if ($(this).attr('type') == 'logout') 
		{
			url = url+'&logout=true';
		}

		$(this).qtip({
			overwrite: false,
			content: {
				title: 'Profil užívateľa',
				text: '<div class="text-align: center;"><img src="/images/web/ajax-loader.gif" alt="Loading..." /></div>',
				ajax: {
					url: url,
					type: 'GET',
					success: function(data,status){
						this.set('content.title', $(data).filter('h3').html());
						this.set('content.text', data);
						this.set('content.button','Zavrieť okno');
						this.set('style.classes','qtip blue userProfilBox');
					}
				}
			},
			events: {
				render: function(event,api){
					// restore default
					api.set('hide.delay',1000);
					api.set('hide.event','mouseleave');

					$(api.elements.content).bind('click',function(ev){
						api.set('hide.delay',false);
						api.set('hide.event',false);
					});
				}
			},
			show: {
				solo: true,
				event: event.type, // Use the same event type as above
				ready: true // Show immediately - important!
			},
			hide: {
				fixed: true,
				delay: 100
			},
			position: {
				corner: {
					target: 'bottomRight',
					tooltip: 'topLeft'
				},
				viewport: $(window)
			},
			style: {
				def: false,
				classes: 'qtip blue',
				tip: {
					corner: false
				}
			}
		});
	});
});