$(function(){
    if( $('ul.orderElmenets').length && $('table.orderTable').length&&$('input.orderUrl').length ){
        var arrow_up = '<i class="fa fa-caret-up"></i>';
        var arrow_down = '<i class="fa fa-caret-down"></i>';
        
        var order_up = '';
        var order_down = '';
        
        $.each($('ul.orderElmenets li'),function(i,a){
            if( $(a).text() != '' && $(a).text() != 'NO_ORDER' ){
                
                order_down = $('input.orderUrl').val()+'&order='+$(a).text()+'&dir=desc';
                order_up = $('input.orderUrl').val()+'&order='+$(a).text()+'&dir=asc';
                
                if( $('#js_str_order').val() == $(a).text() ){
                    $('table.orderTable thead tr td').eq(i).html( '<a href="' + ( $('#js_str_dir').val() == "asc" ? order_down : order_up ) + '" title="up">' + $('table.orderTable thead tr td').eq(i).html() + "&nbsp;&nbsp;" + ( ( $('#js_str_dir').val() == "asc" ) ? arrow_up : arrow_down ) + "</a>" );
                } else {
                    $('table.orderTable thead tr td').eq(i).html( '<a href="' + order_up + '" title="up">' + $('table.orderTable thead tr td').eq(i).html() + "</a>" );
                }
                
                //$('table.orderTable thead tr td').eq(i).append('&nbsp;&nbsp;<a title="down" href="'+ order_down +'">' + arrow_down + '</a>&nbsp;<a title="up" href="'+ order_up +'">' + arrow_up + '</a>');
            }})
    }
});
$(function(){
                if($('span.s_button')){$('span.s_button').hover(function(){
                    $(this).addClass("s_hover")
                },function(){
                    $(this).removeClass("s_hover")
                });
                
                $('span.s_button').on('click',function(){
                    
                    $('span.s_button ul').css('display','none');
                    $('ul',this).css('display','block');
                    
                    $('ul li',this).hover(function(){
                        if($(this).attr('class')!='s_seperator'){
                            $(this).addClass("s_hover");
                        }
                    },function(){
                        if($(this).attr('class')!='s_seperator'){
                            $(this).removeClass("s_hover");
                        }
                    });
                    
                    $('span.s_button').css('z-index','99');$(this).css('z-index','100');$('ul',this).mouseleave(function(){$(this).css('display','none')})})}
});

jQuery.fn.center = function () {
this.css("position","fixed");
this.css("left", ( $(window).width() - this.width() ) / 2 + "px");
this.animate({"top": ( ($(window).height() - this.height() ) / 2) + "px"});
//this.animate({"top": ( ($(window).height() - this.height() ) / 2) + $(window).scrollTop()-60 + "px"});
return this;
}

;(function($){var h=$.scrollTo=function(a,b,c){$(window).scrollTo(a,b,c)};h.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1,limit:true};h.window=function(a){return $(window)._scrollable()};$.fn._scrollable=function(){return this.map(function(){var a=this,isWin=!a.nodeName||$.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!isWin)return a;var b=(a.contentWindow||a).document||a.ownerDocument||a;return/webkit/i.test(navigator.userAgent)||b.compatMode=='BackCompat'?b.body:b.documentElement})};$.fn.scrollTo=function(e,f,g){if(typeof f=='object'){g=f;f=0}if(typeof g=='function')g={onAfter:g};if(e=='max')e=9e9;g=$.extend({},h.defaults,g);f=f||g.duration;g.queue=g.queue&&g.axis.length>1;if(g.queue)f/=2;g.offset=both(g.offset);g.over=both(g.over);return this._scrollable().each(function(){if(e==null)return;var d=this,$elem=$(d),targ=e,toff,attr={},win=$elem.is('html,body');switch(typeof targ){case'number':case'string':if(/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(targ)){targ=both(targ);break}targ=$(targ,this);if(!targ.length)return;case'object':if(targ.is||targ.style)toff=(targ=$(targ)).offset()}$.each(g.axis.split(''),function(i,a){var b=a=='x'?'Left':'Top',pos=b.toLowerCase(),key='scroll'+b,old=d[key],max=h.max(d,a);if(toff){attr[key]=toff[pos]+(win?0:old-$elem.offset()[pos]);if(g.margin){attr[key]-=parseInt(targ.css('margin'+b))||0;attr[key]-=parseInt(targ.css('border'+b+'Width'))||0}attr[key]+=g.offset[pos]||0;if(g.over[pos])attr[key]+=targ[a=='x'?'width':'height']()*g.over[pos]}else{var c=targ[pos];attr[key]=c.slice&&c.slice(-1)=='%'?parseFloat(c)/100*max:c}if(g.limit&&/^\d+$/.test(attr[key]))attr[key]=attr[key]<=0?0:Math.min(attr[key],max);if(!i&&g.queue){if(old!=attr[key])animate(g.onAfterFirst);delete attr[key]}});animate(g.onAfter);function animate(a){$elem.animate(attr,f,g.easing,a&&function(){a.call(this,e,g)})}}).end()};h.max=function(a,b){var c=b=='x'?'Width':'Height',scroll='scroll'+c;if(!$(a).is('html,body'))return a[scroll]-$(a)[c.toLowerCase()]();var d='client'+c,html=a.ownerDocument.documentElement,body=a.ownerDocument.body;return Math.max(html[scroll],body[scroll])-Math.min(html[d],body[d])};function both(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

function getRandID( ID_Name ){
    var RandID = Math.random().toString();
    return '#' + ID_Name + RandID.replace(".","");
}
function timeString( sec ){
    var t = parseInt( sec );
    if( t > 0 ){
        var m = parseInt(t/60);
        if(m>60){
            var h = parseInt(m/60);
            m = m%60;
            var s = t-(h*3600)-(m*60);
            return (h<10 ? ('0'+h) : h) + ':' + (m<10 ? ('0'+m) : m) + ':' + (s<10 ? ('0'+s) : s);
        } else {
            s = t%60;
            return (m<10 ? ('0'+m) : m) + ':' + ((s<10) ? ('0'+s) : s);
        }
    } else return '00:00';
}
function token(){var now = new Date();return now.getDate() + now.getMonth() + now.getFullYear() + now.getHours() + now.getSeconds();}
function confirmation(link,info){if(confirm(info)){window.location=link;}}
$(function(){$('.JS_dynamicLaps .laps .item a').click(function(){$(this).parent().parent().parent().children().removeClass('current');$(this).parent().parent().addClass('current');var directObject = $(this).parent().parent().parent();var contentIndex = $('div.item',directObject).index( $(this).parent().parent() );var globalObject = $(this).parent().parent().parent().parent();$('.lap_item',globalObject).hide();$('.lap_item',globalObject).eq(contentIndex).show();});});
function blinked( el ){
    el.animate({'opacity':'0.1'},300,function(){
        el.animate({'opacity':'1'},300);
        setTimeout(function(){ blinked( el ); },500);
    }); 
}

var dateFormat = function () {
    
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	return function (date, mask, utc) {
		var dF = dateFormat;

		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

        date.setTime

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

function PageError( ErrorText , Header = true )
{
    var ErrorContent = '<div class="bg-danger p10" id="PageGlobalErrorBox">' + ErrorText + '</div>';
    $('#PageGlobalErrorBox').remove();
    
    if( Header )
    {
         $('header').after( ErrorContent );
    }
    else 
    {
        return ErrorContent;    
    }
}

function AlertWindow( Html , AlertType )
{
    
    var Window = $('<div></div>');
    $(Window).addClass('AlertWindow');
    $(Window).attr('id','JsAlertWindow');
    
    var Close = $('<div></div>');
    $(Close).addClass('AlertClose');
    $(Close).append('<a href="javascript:;"><i class="fa fa-remove"></i></a>');
    
    $(Close).click(function(){
        $(Window).fadeOut(function(){
            $(Window).remove();
        });
    });
    
    var CloseLoader = $('<div></div>');
    $(CloseLoader).addClass('AlertCloseLoader');
    
    var Ico = $('<div></div>');
    $(Ico).addClass('AlertIco');
    
    var Content = $('<div></div>');
    $(Content).addClass('AlertContent');
    $(Content).html( Html );
    
    var Clear = $('<div></div>');
    $(Clear).addClass('clear');
    
    var AlertCounter = 0;
    
    $(Window).append( Close );
    $(Window).append( CloseLoader );
    $(Window).append( Ico );
    $(Window).append( Content );
    $(Window).append( Clear );
    
    switch( AlertType )
    {
        case 'danger':
        case 'error':
            $(Window).addClass('AlertError');
            $(Ico).html('<i class="fa fa-times-circle"></i>');
        break;
        
        case 'primary':
        case 'success':
        default:
            $(Window).addClass('AlertSuccess');
            $(Ico).html('<i class="fa fa-check-circle"></i>');
        break;
    }
    
    $('body').append( Window );
    $( Window ).fadeIn();
    
    var CounterProgress = setInterval(function(){
        
        AlertCounter++;
        $('#JsAlertWindow .AlertCloseLoader').css({
            width: AlertCounter + '%'  
        });
        
        if( AlertCounter == 100 )
        {
            clearInterval( CounterProgress );
            $(Window).fadeOut(function(){
                $(Window).remove();
            });
        }
        
    },30);

}

function UsableWindow( Html )
{

    var Window = $('<div></div>');
    $(Window).addClass('UsableWindow');
    $(Window).attr('id','JsUsableWindow');
    
    var Close = $('<div></div>');
    $(Close).addClass('UsableClose');
    $(Close).append('<a href="javascript:;"><i class="fa fa-remove"></i></a>');
    
    $(Close).click(function(){
        $(Window).fadeOut(function(){
            $(Window).remove();
        });
    });
    
    
    var Ico = $('<div></div>');
    $(Ico).addClass('UsableIco');
    
    var Content = $('<div></div>');
    $(Content).addClass('UsableContent');
    $(Content).html( Html );
    
    var Clear = $('<div></div>');
    $(Clear).addClass('clear');

    
    $(Window).append( Close );
    $(Window).append( Ico );
    $(Window).append( Content );
    $(Window).append( Clear );

    
    $('body').append( Window );
    $( Window ).fadeIn();
    

}

function CloseUsableWindow()
{
    $('#JsUsableWindow').fadeOut(function(){
        
        $(this).remove();
         
    });
}

$(function(){

    $(document).on('click','.UsableTrigger',function(){
         if( $(this).attr('data-usable-params') )
         {
            var UsableParams = $(this).attr('data-usable-params');
            $.getJSON('ajax.php?' + UsableParams,function(response){
                
                if( response.status )
                {
                    UsableWindow( response.html );
                } 
                else 
                {
                    AlertWindow( response.error , 'danger' );
                }
                
            });
         } 
         else 
         {
            if( $(this).attr('data-usable-target') )
            {
                var Target = $(this).attr('data-usable-target');
                var TargetContent = $(Target).html();
                UsableWindow( TargetContent );
            }
         }
    });
    
    $('#toNewsletter').click(function(){
        
        console.log('Click .toNewsletter');
        
        $.getJSON('ajax.php?' + $('#HomeNewsletterForm').serialize(),function(response){
            
            console.log('Form params: ' + $('#HomeNewsletterForm').serialize() );
            
            if( response.status )
            {
                AlertWindow( response.msg , ( response.FormStatus ? 'success' : 'danger' ) );
            } 
            else 
            {
                AlertWindow( response.error , 'danger' );
            }
            
        });
        
    });
    
    $(window).scroll(function (event) {
        
        var ScrollPosition = $(window).scrollTop();
        if( $('header').hasClass('HomeHeader') )
        {
            if( ScrollPosition >= 500 )
            {
                $('header').css({
                    background: 'rgba(0,0,0,0.7)'
                });

            } 
            else 
            {
                $('header').css({
                    background: 'rgba(0,0,0,0.3)'
                });

            }
            
            if( ScrollPosition > 0 )
            {
                $('.HomeSliderChoose').fadeOut();
            } 
            else 
            {
                $('.HomeSliderChoose').fadeIn();
            }
        }
        

        
        
    });
    
    
});

var LastContentTarget = false;

function LoadDynamicPage( DynamicUrl , ContentTarget )
{
    
    SelfPreloader('','#LoadDynamicPage')
    
    LastContentTarget = ContentTarget;
    
    $.getJSON(DynamicUrl,function(response){
       
       if( response.status )
       {
            $(ContentTarget).html( response.html );
            $(ContentTarget + ' .pagination a, .DynamixXhr').attr('href',function(){
                $(this).attr('data-xhr-url',$(this).attr('href')); 
                $(this).attr('href','javascript:;'); 
            });
            
            $(ContentTarget + ' a').click(function(){
                LoadDynamicPage( $(this).attr('data-xhr-url') , ContentTarget );
            });
            
            SelfPreloaderClose( '#LoadDynamicPage' );
       } 
       else 
       {
            AlertWindow( response.error , 'danger' );
       }
        
    });
}

$(function(){
   
   $('.AdminArea').hover(function(){
        $('.AdminArea .fa-cog').addClass('fa-spin');
   },function(){
        $('.AdminArea .fa-cog').removeClass('fa-spin');
   }); 
});

$(document).on('click','.DynamixXhr',function(){
    LoadDynamicPage( $(this).attr('data-xhr-url') , LastContentTarget );
});

$(document).on('click','form .DynamicFormSubmit',function(){
    
    //var DynamicFormUrl = 'ajax.php?' + $(this).closest('form').serialize() + '&btndata=' + $(this).attr('data-btn');
    
    var Button = $(this);
    var DynamicFormUrl = 'ajax.php?' + $(this).closest('form').serialize() + '&btndata=' + $(this).attr('data-btn');
    
    LoadDynamicForm( DynamicFormUrl , Button );
    
});

function LoadDynamicForm( url , Button )
{
    var ButtonStorage = $( Button ).html();
    
    $( Button ).html('<i class="fa fa-circle-o-notch fa-spin"></i> Czekaj...');
    
    var DynamicFormTarget = $( Button ).closest('.DynamicForms');
    
    $.getJSON( url , function( response ){
        
        if( response.status )
        {
            $( DynamicFormTarget ).html( response.html );
            if( response.refresh )
            {
                window.location.reload();
            }
        } 
        else 
        {
            AlertWindow( response.error , 'danger' );
        }
        
        $( Button ).html( ButtonStorage );
         
    });  
}



$(function(){
    $('body').tooltip({
        selector: '.SetTooltip'
    });
})

$(document).on('click','[data-image]',function(){
   
   var Handler = $('<div id="ImageZoom"></div>');

   $( Handler ).css({
        'width': '100%',
        'position': 'fixed',
        'left': '0px',
        'top': '0px',
        'bottom': '0px',
        'background': 'rgba(0,0,0,0.7)',
        'z-index': '9999',
        'text-align': 'center',
        opacity: 0 
   }); 
   
   $('body').append( Handler );
   $(Handler).animate({
        opacity: 1
   });
   
   var ImageSrc = $(this).attr('data-image');
   
   var ImageWrapper = $('<div id="ImageZoomWrapper"></div>');
   $('#ImageZoom').html( ImageWrapper );
   $( ImageWrapper ).css({
        'display': 'inline-block',
        'padding': '10px',
        'background': '#fff',
        'margin': '0 auto',
        '-webkit-border-radius': '5px',
        '-moz-border-radius': '5px',
        'border-radius': '5px'
   });

    

   var Image = $('<img src="' + ImageSrc + '" />');

   $('#ImageZoomWrapper').html( Image );

    var ImageWidth = parseInt( $('#ImageZoomWrapper img').width() );
    var HandlerWidth = parseInt( $(Handler).width() );
    
    if( ImageWidth > HandlerWidth )
    {
        var Proportion = ( HandlerWidth / 4 ) * 3;
        $(Image).css({
            'width': Proportion
        });
    }
    
    var ImageHeight = parseInt( $('#ImageZoomWrapper img').height() );
    var HandlerHeight = parseInt( $(Handler).height() );
    
    var FreeSpace = HandlerHeight - ImageHeight;
    if( FreeSpace > 0 )
    {
        FreeSpace = FreeSpace/2 - 20;
        if( FreeSpace > 0 )
        {
            $('#ImageZoom').css({
               paddingTop: FreeSpace + 'px' 
            });
        }
    }
   
});

$(document).on('click','#ImageZoom',function(){
   var ZoomFrame = $(this); 
   $(ZoomFrame).fadeOut(400,function(){
        $(ZoomFrame).remove();
   });
});

$(document).on('click','.ShowHidePassword',function(){
  if( $('[name=password]').attr('type') == 'password' )
  {
    $(this).html('<i class="fa fa-eye"></i> Ukryj hasło');
    $('[name=password]').attr('type','text');
  } 
  else 
  {
    $(this).html('<i class="fa fa-eye"></i> Pokaż hasło');
    $('[name=password]').attr('type','password');
  }
});