String.prototype.strim = function(s) {
	var t = this;

	if (typeof(s) == undefined) {
		return t.trim();
	}

    if (t[0] == s) {
        t = t.substr(1, t.length - 1);
    }

    if (t[t.length - 1] == s) {
        t = t.substr(-t.length, t.length - 1);
    }

    return t;
};

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame    ||
            window.oRequestAnimationFrame      ||
            window.msRequestAnimationFrame     ||
   	function(callback, element){
    	window.setTimeout(callback, 1000/60);
	};
})();

/* functionality testing */
var drag_test = function() {
	var div = document.createElement('div');
	return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};

var filereader_test = function() {
	return (typeof(window.FileReader) != 'undefined');
};

/* Variables */
var windW, mainH, done, counterCarouselW, counter, sub, fancyContent;

/* carouFredSel initialize */
var carouselInitialize = function() {
    $('.carousel').each(function() {
        $(this).find('ul').carouFredSel({
            auto : false,
            width: '100%',
            prev : {
                button : function() {
                    return $(this).parents('.carousel').find('.prev');
                }
            },
            next : {
                button : function() {
                    return $(this).parents('.carousel').find('.next');
                }
            },
            swipe : {
                onTouch : true,
                onMouse : true
            },
			pagination : {
				container : $(this).find('.pager .auto'),
				anchorBuilder : function() {
					return '<a href="#"><span>' + $(this).attr('alt') + '</span></a>';
				}
			},
            scroll : {
                fx : 'slide',
                items : 1,
                duration : 500
            },
            items : {
                visible : {
                    min : 1,
                    max : 5
                }
            },
            onCreate : function() {
            	$(this).parents().removeClass('tempHeight');
    			$(this).parents().find('.preloader').remove();
            }
        });
    });
};

/* carouFredSel initialize */
var oneItemCarouselInitialize = function() {
    $('.oneItemCarousel').each(function() {
        $(this).find('ul').carouFredSel({
            auto : false,
            responsive : true,
            width : '100%',
            height: 'variable',
            prev : {
                button : function() {
                    return $(this).parents('.oneItemCarousel').find('.prev');
                }
            },
            next : {
                button : function() {
                    return $(this).parents('.oneItemCarousel').find('.next');
                }
            },
            swipe : {
                onTouch : true,
                onMouse : true
            },
			pagination : {
				container : $(this).find('.pager'),
				anchorBuilder : function() {
					return '<a href="#"></a>';
				}
			},
            scroll : {
                fx : 'slide',
                items : 1,
                duration : 900
            },
            items : {
            	visible : 1,
            	height : 'variable'
            },
            onCreate : function() {
            	$(this).parents().removeClass('tempHeight');
    			$(this).parents().find('.preloader').remove();
            }
        });
    });
};

/* carouFredSel initialize */
var textCarouselInitialize = function() {
    $('.textCarousel').each(function() {
        $(this).find('ul').carouFredSel({
            auto : false,
            responsive : true,
            prev : {
                button : function() {
                    return $(this).parents('.carousel').find('.prev');
                }
            },
            next : {
                button : function() {
                    return $(this).parents('.carousel').find('.next');
                }
            },
            scroll : {
                fx : 'fade',
                items : 1,
                duration : 900
            },
            items : {
            	visible : 1
            },
            onCreate : function() {
            	$(this).parents().removeClass('tempHeight');
    			$(this).parents().find('.preloader').remove();
            }
        });
    });
};

/* two rows carousel initialize */
var twoRowsCarouselInitialize = function() {
	windW = $(window).width();

	if (windW <= '952') {
		$('.twoRowsCarousel ul').carouFredSel({
            auto : false,
            width: '100%',
            prev : {
                button : function() {
                    return $(this).parents('.twoRowsCarousel').find('.prev');
                }
            },
            next : {
                button : function() {
                    return $(this).parents('.twoRowsCarousel').find('.next');
                }
            },
            swipe : {
                onTouch : true,
                onMouse : true
            },
            scroll : {
                fx : 'slide',
                items : 1,
                duration : 900
            },
            items : {
                visible : {
                    min : 1,
                    max : 5
                }
            },
            onCreate : function() {
            	$(this).parents().removeClass('tempHeight');
    			$(this).parents().find('.preloader').remove();
            }
        });
	} else if (windW >= '953') {
		$('.twoRowsCarousel ul').trigger('destroy');
	}
};

/* fancybox initialize */
var fancyBoxInitialize = function() {
	$('.fancy').fancybox({
		tpl : {
			wrap : '<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',
			image : '<img class="fancybox-image" src="{href}" alt="" />',
			error : '<p class="fancybox-error">Изображение не найдено.<br/>Попробуйте позже.</p>',
			closeBtn : '<a class="fancybox-close" href="javascript:;"></a>',
			next : '<a class="fancybox-next" href="javascript:;"></a>',
			prev : '<a class="fancybox-prev" href="javascript:;"></a>'
		},
		'showNavArrows' : true
	});
};

/* minimal width functions initialize */
var minWidthFunctionsInitialize = function() {
    windW = $(window).width();
    mainH = $('.main').height();

    if(windW <= 800) {
        $('.mainNav').css('height',mainH);

    } else {
        $('.mainNav').css('height','auto');
    }
};

var smoothscroll = function(obj) {
	if (obj.offset() == undefined) return false;
	$('html, body').stop().animate({
		'scrollTop' : obj.offset().top
	}, 500, 'swing');
};

/* inventary popup initialize */
var fancyBoxInventoryInitialize = function() {
	$('.fancyInventory').fancybox({
		tpl : {
			wrap : '<div class="fancybox-wrap fancy-inventory" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',
			closeBtn : '<a class="fancybox-close" href="javascript:;"></a>',
			next : '<a class="fancybox-next" href="javascript:;"></a>',
			prev : '<a class="fancybox-prev" href="javascript:;"></a>'
		},
		'showNavArrows' : true,
		beforeShow : function() {
		    this.title = (this.index + 1) + '/' + this.group.length;
		}
	});
};

/* carousel with counter initialize */
var counterCarouselInitialize = function() {
	var carousel = $('.counterCarousel');
	if (carousel.length) {
		carousel.carouFredSel({
	        auto : false,
	        responsive : true,
	        width : '100%',
	        height: 'variable',
	        prev : {
	            button : function() {
	                return $(this).parents('.inventoryItems').find('.prev');
	            }
	        },
	        next : {
	            button : function() {
	                return $(this).parents('.inventoryItems').find('.next');
	            }
	        },
	        scroll : {
	            fx : 'slide',
	            items : 1,
	            duration : 900,
	            onAfter : function(data) {
		            $(this).trigger('currentPosition', function(pos) {
		                counter = (pos+1) + '/' + $('>', this).length;
		                $(this).parents('.inventoryItems').find('.counter').html(counter);
		            });
	            }
	        },
	        onCreate : function(data) {
	        	$(this).trigger('currentPosition', function(pos) {
	                counter = (pos+1) + '/' + $('>', this).length;
	                $(this).parents('.inventoryItems').find('.counter').html(counter);
	            });
	        },
	        items : {
	        	visible : 1,
	        	height: 'variable'
	        }
	    });
	}
};

/* fading carousel initialize */
var fadingCarouselInitialize = function() {
	var carousel = $('.fadingCarousel ul');
	if (carousel.length) {
		carousel.carouFredSel({
	        auto : false,
	        width: '100%',
	        scroll : {
	            fx : 'fade',
	            items : 1,
	            duration : 900
	        },
	        items : 1
	    });
	}
};

/* logout */
var logout_t = true;
var logout = function() {
	if (logout_t) {
		logout_t = false;
		$.post(window.location, {
			token: GLOBAL.token,
			mode: 'logout'
		}, function(res) {
			logout_t = true;
			window.location.href = '/';
		});
	}
};

/* DOM Ready Functions */
jQuery(document).ready(function($) {
	IMAGE_LOAD = '<img src="' + GLOBAL.stat_path + 'images/ajax_clock_small.gif" alt="" />';

	/*
	* Open basic error dialog
	* @tested ok
	*/
	DIALOG_ERROR = function(content) {
		$.toast.options.position = 'top-right';
		$.toast.options.loaderBg = 'orange';
		$.toast.options.textColor = 'white';
		$.toast.options.bgColor = '#868686';
		$.toast.options.hideAfter = 60000;
		$.toast(content);
	};

	/*
	* Button disable and load effect helper
	* @tested ok
	*/
	BUTTON_LOAD = function(btn, state) {
		btn.disabled = state;
		if (state) btn.def = btn.innerHTML;
		btn.innerHTML = state ? IMAGE_LOAD : btn.def;
	};

	/*
	 * XHR requester
	 * @tested ok
	 */
	XHR_REQUEST = function(emitter, data, on_success, on_error, get_raw) {
		var xhr_data = {
			token : GLOBAL.token,
			mode : emitter.name
		};

		for (var k in data) {
			xhr_data[k] = data[k];
		}

		BUTTON_LOAD(emitter, true);
		$.post({
			url: document.baseURI,
			data: xhr_data,
			success: function(res) {
				BUTTON_LOAD(emitter, false);
				if (!get_raw && isNaN(parseInt(res))) {
					DIALOG_ERROR(res);
				} else {
					if (get_raw || res == 1) {
						if ($.isFunction(on_success)) {
							on_success.call(emitter, res);
						}
					} else {
						DIALOG_ERROR(errors[res]);
					}
				}
			},
			error: function(xhr) {
				BUTTON_LOAD(emitter, false);
				var res = $.parseJSON(xhr.responseText);
				DIALOG_ERROR('<pre>' + res.error + '</pre>');
				if ($.isFunction(on_error)) {
					on_error.call(emitter, res);
				}
			}
		});
	};

	$.fn.multiVal = function() {
		var res = [];
		$(this).each(function(i) {
			res[i] = this.value;
		});
		return (res.length > 1) ? res : res[0];
	};

	$.fn.advTitle = function() {
		$(this).each(function() {
			var my_tooltip = null, gc_interval = null;
			$(this).mouseover(function(mouse) {
				this.x_title = this.title;
				this.title = '';

				my_tooltip = $('<div class="advTitle"><p>'+html_entity_decode(this.x_title)+'</p></div>');
				$('body').append(my_tooltip);

				my_tooltip.css({left : mouse.pageX, top : mouse.pageY + 19}).show();
				gc_interval = setInterval(function() {
					this.title = htmlentities(this.x_title);
					this.x_title = '';
					my_tooltip.remove();
				}, 9000);
			}).mouseout(function() {
				if (my_tooltip) {
					this.title = htmlentities(this.x_title);
					this.x_title = '';
					my_tooltip.remove();
				}
			});
		});
	};

	if ($('.tablink').length) {
		var tab = function(id) {
			$('.tablink').removeClass('active');
			$('.tab').hide();
			$('.tab[data-group="'+id+'"]').show();
			$('.tablink[data-group="'+id+'"]').addClass('active');
		}

		if (document.location.hash.length > 0) {
			tab(jQuery('.tablink[href="'+document.location.hash+'"]').data('group'));
		}

		$('.tablink').click(function() {
			tab(this.dataset.group);
		});
	}

	$('.rda').change(function() {
		document.location.href = $(this).children('option:selected').attr('value');
	});

	$('.logout').click(function() {
		logout();
	});

	$('.percentage').each(function() {
		done = $(this).find('.done').attr('data-done');
		$(this).find('.done').animate({
			'width' : done + '%'
		},1500);
	});

	$('.fancyInventory').click(function() {
		$(this).attr('href').substr(start[1,1]);
	});

	//Attach
    $('.attach').find('button').click(function() {
        $(this).siblings('input[type="file"]').trigger('click');
    });

	$('.attach input[type="file"]').each(function() {
		$(this).change(function(e) {
			var files = e.target.files;

			for (var i = 0, f; f = files[i]; i++) {

				// Only process image files.
				if (!f.type.match('image.*')) {
					continue;
				}

				var reader = new FileReader();

				// Closure to capture the file information.
				reader.onload = (function(theFile) {
					return function(e) {
						// Render thumbnail.
						var span = document.createElement('span');
						span.innerHTML = ['<img class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
						document.getElementById('avatar').insertBefore(span, null);
					};
				})(f);

				// Read in the image file as a data URL.
				reader.readAsDataURL(f);
			}

			var value = $(this).val();
			var a = value.split('\\');
			var r = a[a.length - 1];
			$(this).parents('.buttons').find('.path').text(r);
		});
	});

	if (windW <= 768) {
		$('.inventoryItems li a').addClass('fancyInventory');
	} else if(windW >= 769) {
		$('.inventoryItems li a').removeClass('fancyInventory');
	}

	$.fn.scrollToTop = function() {
		$(this).hide().removeAttr("href");
		if ($(window).scrollTop() >= "1000") {
			$(this).fadeIn("slow");
		}
		var scrollDiv = $(this);
		$(window).scroll(function() {
			if ($(window).scrollTop() <= "999") {
				$(scrollDiv).fadeOut("slow");
			} else if($(window).scrollTop() >= "1000") {
				$(scrollDiv).fadeIn("slow");
			}
		});
		$(this).click(function() {
			$("html, body").animate({
				scrollTop : 0
			}, "slow");
		});
	};

	$("#toTop").scrollToTop();

	//Fancybox
	fancyBoxInitialize();

	minWidthFunctionsInitialize();

	fancyBoxInventoryInitialize();

	//Tabs
    $('ul.tabs').delegate('li:not(.current)', 'click', function(e) {
        $(this).addClass('current').siblings().removeClass('current');
        $(this).parents().find('.box').eq($(this).index()).fadeIn(150).siblings('.box').hide();
    });

    $('ul.tabs > li > a').click(function(e) {
        e.preventDefault();
    });

    $('.buttons .remove').click(function() {
        $(this).parents('.buttons').find('.path').html('');

		$(this).parents('.avatarChoose').find('.img span').remove();

        return false;
    });
});

/* Page Load Functions */
$(window).load(function() {
	//// todo: This shit require use RequestAnimation API instead of setinterval\timeout

	setInterval(function() {
		setTimeout(function() {
			$('.blink_red').css({
				'color' : '#646464',
				'border' : '1px solid #979797'
			}).children().css({
				'padding' : '4px 6px 0'
			});
		}, 1000);

		$('.blink_red').css({
			'color' : 'red',
			'border' : '2px solid red'
		}).children().css({
			'padding' : '3px 5px 0'
		});
	}, 2000);

	$('*[title]').advTitle();

	////

	var interval_id, processed = false;

	$('.resend_confirm').click(function() {
		var t = new tpc(this, 'color:#909090;', 50);
		t.start();
		if (!processed) {
			processed = true;
			$.post($.ajaxSettings.url, {
				mode 	: 'resend_confirm',
				action	: action,
				token 	: GLOBAL.token
			}, function(d) {
				processed = false;
				t.stop();
				if (isNaN(parseInt(d))) {
					d = $.parseJSON(d);
					reset_errors();
					$('.explain').append('<p class=\"errors\"><br /><span class=\"error\">'+LANG.ERROR_OPERATION_TIMEOUT_DESC+'<\/span><\/p>');
					if (interval_id) clearInterval(interval_id);
					countdown($.find('.autotimer')[0], d['estimated']);
				} else {
					d = parseInt(d);
					if (!d) {
						reset_errors();
						$('.explain').append('<p class=\"errors\"><br /><span class=\"red\">'+LANG.AN_ERROR_OCCURED_TRY_AGAIN_FIRST+'<\/span><\/p>');
					} else {
						reset_errors();
						$('.explain').append('<p class=\"errors\"><br /><span class=\"green\">'+LANG.CODE_SENDED_AGAIN+'<\/span><\/p>');
					}
				}
			});
		}
	});

	function reset_errors() {
		var e = $.find('.errors');
		if (e.length) {
			e[0].remove();
		}
	}

	function countdown(element, init) {
		interval_id = setInterval(function() {
			element.innerHTML = init--;
			if (!init) {
				clearInterval(interval_id);
				reset_errors();
			}
		}, 1000);
	}

	function tpc(selector, css, int) {
		this.pid = false;
		this.int = int;
		this.css = css;
		this.sel = selector;

		this.start = function() {
			var self = this;
			var t = jQuery(self.sel)[0].innerHTML;
			var p = 0;
			this.pid = setInterval(function() {
				if (typeof(t[p]) != 'undefined') {
					t = jQuery(self.sel)[0].innerHTML.replace(/<\/?[^>]+>/gi, '').split('');
					t[p] = '<span style=\"'+self.css+'\">'+t[p]+'<\/span>';
					jQuery(self.sel)[0].innerHTML = t.join('');
					p++;
				} else {
					p = 0;
				}
			}, this.int);
		};

		this.stop = function() {
			var self = this;
			clearInterval(self.pid);
			self.pid = false;
		};
	}

	////

	$('#innerThumbs ul li a').click(function() {
        $('#detail ul').trigger('slideTo', '#' + this.href.split('#').pop());
        $('#innerThumbs ul li').removeClass('current');
        $(this).parent().addClass('current');
        return false;
    });

	$('.counterCarousel > div').css('width', $('.inventoryItems').width());

	//Custom Select
	$('.hasSelect button, .hasSelect .button').click(function() {
		$(this).parents('.hasSelect').find('ul').slideToggle(100);
	});

	//Carousel
	carouselInitialize();

    $('.carousel').each(function() {
        $(this).find('.preloadImg').remove();
    });

    oneItemCarouselInitialize();
    textCarouselInitialize();
    twoRowsCarouselInitialize();
	counterCarouselInitialize();
	fadingCarouselInitialize();

    $('#thumbs ul li a').mousedown(function(e) {
    	e.preventDefault;
        $('#about ul').trigger('slideTo', '#' + this.href.split('#').pop());
        $('#thumbs ul li').removeClass('current');
        $(this).parent().addClass('current');
        return false;
    }).click(function(e) {
    	e.preventDefault;
    	return false;
    }).contextmenu(function(e) {
    	e.preventDefault;
    	return false;
    });

	//Custom Scrollbar
    $('.verticalScrollBar').mCustomScrollbar({
        scrollInertia : 150,
        contentTouchScroll : true
    });

    $('.horizontalScrollBar').mCustomScrollbar({
        horizontalScroll : true
    });

    // Spoiler
    $('.spoil_control').click(function() {
    	var spoil = $(this).next('.spoiler');
    	if (spoil.css('display') == 'none') {
    		spoil.show();
    	} else {
    		spoil.hide();
    	}
    });

    // Captcha
	jQuery('.cap_image').click(function(e) {
    	var now = new Date();
    	jQuery.get('\/captcha\/?' + now.getTime(), {}, function(res) {
    		e.target.src = res;
    	});
    });

    //Trigger Navbar
    $('.triggerNav').click(function() {
        $('.main').toggleClass('animateRight');

        if($('.animateRight').length >= 1) {
            $('.wrapper').animate({
                'right' : 240
            });
            $('#footer').animate({
                'right' : 240
            });
        } else {
            $('.wrapper').animate({
                'right' : 0
            });
            $('#footer').animate({
                'right' : 0
            });
        }
    });

    //Smoothscrolling
    $('.smoothscroll').click(function(e) {
    	e.preventDefault();
		let scrollTo = e.target.dataset.scroll
    	t = $('div.'+scrollTo);
    	smoothscroll(t);
    });
});

$(window).resize(function() {
	var windW = $(window).width();
	twoRowsCarouselInitialize();
	carouselInitialize();

	if(windW <= 768) {
		$('.inventoryItems li a').addClass('fancyInventory');
	} else if(windW >= 769) {
		$('.wrapper').css('right','0');
		$('.inventoryItems li a').removeClass('fancyInventory');
	}
});

/**
 * Fast string.format(...args) implementation
 * Based on FSM and use string to array conversion as more quickly
 * %s, %d - only supported now
 * No ES6 tricks used for compatibility
 */
if (typeof(String.prototype.format) == 'undefined') {
	String.prototype.format = function() {
		var str = this.split(''), i = -1, fmt = '', state = false;
		for (var p in str) {
			if (str[p] == '%') {
				state = true;
				i++;
			} else {
				switch (str[p]) {
					case 's':
						if (state) {
							fmt += arguments[i];
							state = false;
						} else {
							fmt += str[p];
						}
						break;

					case 'd':
						if (state) {
							fmt += parseInt(arguments[i]);
							state = false;
						} else {
							fmt += str[p];
						}
						break;

					default:
						state = false;
						fmt += str[p];
						break;
				}
			}
		}
		return fmt;
	};
}
