$(document).ready(function() {
	$(document).pngFix();
	fieldsInit();
	boxInit();
});

function str_replace(sSearch, sReplace, sString) {
	for (var i = 0; i < sString.length; i++)
		if (sString.substring(i, i + sSearch.length) == sSearch)
			sString = sString.substring(0, i) + sReplace + sString.substring(i + sSearch.length, sString.length);

	return sString;
}

function trim(sStr, sSym) {
	var sSym = (sSym == undefined) ? ' ' : sSym,
		rReg1 = new RegExp('\\' + sSym + '{2,}', 'gi');
		rReg2 = new RegExp('^\\' + sSym + '+', 'gi');
		rReg3 = new RegExp('\\' + sSym + '+$', 'gi');

	sStr = sStr.replace(rReg1, sSym);
	sStr = sStr.replace(rReg2, '');
	sStr = sStr.replace(rReg3, '');

	return sStr;
}

function in_array(sWhat, aWhere) {
	for (var i = 0; i < aWhere.length; i++)
		if (sWhat == aWhere[i])
			return true;

	return false;
}

function fieldsInit(sSel) {
	var sSel = (sSel == undefined) ? 'input.default, textarea.default' : sSel;
	var oItems = $(sSel);

	if (oItems.length) {
		var sClass = 'unfocused';

		oItems.each(function() {
			var oThis = $(this);

			oThis.addClass(sClass).attr('title', oThis.val());
		});
	
		oItems.bind('focus', function() {
			var oThis = $(this);

			if (oThis.val() == oThis.attr('title'))
				oThis.removeClass(sClass).val('');
		});

		oItems.bind('blur', function() {
			var oThis = $(this);

			if (oThis.val() == '')
				oThis.addClass(sClass).val(oThis.attr('title'));
		});
	}
}

function mailValid(sMail) {
	sMail = sMail.replace(/^\s+|\s+$/g, '');

	return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,6}$/i).test(sMail);
}

function boxClear() {
	var oItem = $('#cboxLoadedContent');

	if (oItem.length)
		oItem.remove();

	if (top.CKEDITOR != undefined && CKEDITOR.instances['insiteEditor']) {
		CKEDITOR.remove(CKEDITOR.instances['insiteEditor']);
		delete oEditor;
	}
}

function boxInit(sSel) {
	if (sSel == undefined){
		var sSel = 'a.box';

		$('a.box2').colorbox({ width: '950px', height: '450px' });
		$('a.box3').colorbox({ width: '950px', maxHeight: '450px' });
	}

	boxClear();
	$(sSel).colorbox({ maxWidth: '950px', maxHeight: '450px' });
}

function ckeInit() {
	if (top.oEditor != undefined) {
		oEditor.destroy();
		oEditor = null;
	} else {
		CKEDITOR.config.customConfig = $('base').attr('href') + 'plugins/ckeditor/config_simple.js';
		oEditor = CKEDITOR.replace('insiteEditor', {
			filebrowserBrowseUrl: $('base').attr('href') + 'plugins/filemanager/index.html'
		});
	}
}

function upload(oThis, sFolder, sEditUrl, sCompleteFunc, sFileExt, iLimit) {
	var oOptions = {
		'script':			'/plugins/uploadify/uploadify.php',
		'uploader':			'/plugins/uploadify/uploadify.swf',
		'cancelImg':		'/plugins/uploadify/cancel.png',
		'folder':			'/' + sFolder,
        'fileExt':			(sFileExt == undefined) ? '*.jpg;*.jpeg;*.png;*.gif' : sFileExt,
		'sizeLimit':		3072000, // 3 Mb
		'queueSizeLimit':	(iLimit == undefined) ? 100 : iLimit,
		'multi':			true,
		'auto':				true,
		'onSelectOnce':		function() {
								sUplFiles = '';
							},
		'onComplete':		function(event, fileObj, data, response) {
								sUplFiles += response + ';';
							},
		'onAllComplete':	function(event, data) {
								alert('Файлы загружены, начинается их обработка. Нажмите ОК и дождитесь уведомления о завершении операции.');

								sUplFiles = sUplFiles.substring(0, sUplFiles.length - 1);

								$.ajax({
									url: sEditUrl,
									type: 'post',
									data: 'files=' + sUplFiles,
									success: function() {
										alert('Обработка файлов завершена');
										eval(sCompleteFunc);
									}
								});
							}
	};

	var oUpl = $('#insiteUplBtnUploader'),
		oThis = $(oThis);

	if (oUpl.length) {
		oUpl.remove();

		$('#insiteUplBtn').remove();
		$('#insiteUplBtnQueue').remove();
		$('a.insiteUpl').show();
	}

	oThis.after('<input type="file" name="photo" id="insiteUplBtn">').hide();
	$('#insiteUplBtn').uploadify(oOptions);
}

function addFiles(sFiles, sSel, sFolder) {
	var sFiles = str_replace(';', ',', sFiles);
	sFiles = str_replace('/' + sFolder + '/', '', sFiles);

	var oItem = $(sSel),
		aFiles = sFiles.split(','),
		sHtml = '';

	for (var i = 0; i < aFiles.length; i++)
		sHtml += '<li><input type="checkbox" class="insiteCheck" value="' + aFiles[i] + '" onclick="javascript:checkFiles(this,\'' + sSel + '\')" checked="checked"> <img src="' + sFolder + '/' + aFiles[i].replace(/\./, '_thumb.') + '" alt=""></li>';

	$('#oldForm').append(sHtml);
	oItem.val(oItem.val() ? oItem.val() + ',' + sFiles : sFiles);
}

function checkFiles(oThis, sSel) {
	var oThis = $(oThis),
		sFile = oThis.val(),
		oItem = $(sSel),
		aFiles = oItem.val().split(',');

	if (oItem.val().indexOf(sFile) != -1) {
		for (var i = 0; i < aFiles.length; i++)
			if (aFiles[i] == sFile) {
				delete aFiles[i];
				break;
			}
	} else
		aFiles.push(sFile);

	var sFiles = aFiles.join(',');
	sFiles = trim(sFiles, ',')

	oItem.val(sFiles);
}

function formSubmit(sId) {
	$('#' + sId).submit();
}

function captchaReload(sId) {
	$('#' + sId).attr('src', 'plugins/kcaptcha/index.php?rand=' + Math.random());
}

function winRefresh() {
	var aUrl = window.location.href.split('#');
	window.location.href = window.location.hash ? aUrl[0] : window.location.href;
}

function winResize() {
	$.colorbox.resize({ width: '100%', height: '100%' });

	var oEditor = $('#insiteEditor');

	if (oEditor.length)
		oEditor.css('width', '98%');
}

function logout() {
	if (window.confirm('Вы уверены, что хотите выйти?'))
		$.ajax({
			url: $('base').attr('href') + 'user/logout',
			success: function() {
				winRefresh();
			}
		});
}

function login() {
	boxClear();
	$.colorbox({ href: 'box/login', title: 'Авторизация' });
}

function reg() {
	boxClear();
	$.colorbox({ href: 'box/reg', title: 'Регистрация' });
}

function rem() {
	boxClear();
	$.colorbox({ href: 'box/rem', title: 'Восстановление пароля' });
}

/*function subMenu(sSel) {
	var sSel = (sSel == undefined) ? '#menu' : sSel;
	var oItems = $(sSel + ' li');

	if (oItems.length)
		oItems.each(function() {
			var oThis = $(this);
			var oSub = oThis.children('div:first');

			if (oSub.length)
				oThis.hover(function() {
					oSub.slideDown();
				},
				function() {
					oSub.slideUp();
				});
		});
}

function onClick(sSel) {
	var sSel = (sSel == undefined) ? '#menu' : sSel;
	var oItems = $(sSel + ' li');

	if (oItems.length) {
		var sUrl = $('base').attr('href');

		oItems.each(function() {
			var oThis = $(this);

			oThis.click(function() {
				window.location.href = sUrl + oThis.children('a').attr('href');
				return false;
			});
		});
	}
}

function faqHide() {
	var oItem = $('ol#faq');

	if (oItem.length) {
		oItem.find('div.ans').addClass('hid');
		faq();
	}
}

function faq(iId) {
	if (iId == undefined && window.location.hash) {
		var aUrl = window.location.hash.split('#q');
		var iId = Number(aUrl[1]);
	}

	if (iId != undefined) {
		var oItem = $('#faq');
		var oCur = oItem.find('div.ans:eq(' + (iId - 1) + ')');
		var oOld = oItem.find('div.ans:not(:eq(' + (iId - 1) + '))');

		oOld.addClass('hid');
		oOld.parent().removeClass('cur');

		if (!oCur.hasClass('hid')) {
			oCur.parent().removeClass('cur');
			oCur.addClass('hid');
		} else {
			oCur.parent().addClass('cur');
			oCur.removeClass('hid');
		}
	}
}

function cabinet(sTab, mParam1) {
	var sUrl = 'user/cabinet';
	sUrl += (sTab != undefined) ? '/' + sTab : '/person';
	sUrl += (mParam1 != undefined) ? '/' + mParam1 : '';
	sUrl += '/?rand=' + Math.random();

	boxClear();
	$.colorbox({ href: sUrl, title: 'Личный кабинет', maxWidth: '950px', maxHeight: '450px' });
}

function basket(iId) {
	var iId = (iId == undefined) ? 0 : iId;

	if (iId && top.iUserId == undefined && window.confirm('Авторизуйтесь, чтобы добавить товар в корзину. Открыть форму авторизации?'))
		login();
	else if (top.iUserId != undefined)
		$.ajax({
			url: $('base').attr('href') + 'shop/basket/' + iId + '/',
			cache: false,
			success: function(iCount) {
				basketCounter(iCount);

				if (iId)
					alert('Товар добавлен');
			}
		});
}

function basketCounter(iCount) {
	if (iCount == '0')
		var sHtml = 'Ваша корзина пуста';
	else
		var sHtml = '<a href="javascript:order()" class="dhtml">Ваша корзина</a> ' + iCount;

	$('#basket').html(sHtml);
}

function order() {
	boxClear();
	$.colorbox({ href: 'shop/order/?rand=' + Math.random(), title: 'Ваша корзина', maxWidth: '950px', maxHeight: '450px' });
}

function orderCheck(iId, sPage) {
	var sPage = sPage ? sPage : 'cab';
	var sBack = (sPage == 'cab') ? "<a href=\"javascript:cabinet('orders')\">Заказы</a>" : "<a href=\"javascript:insiteOrders('" + sPage + "')\">Модерация заказов</a>";
	var sTitle = sBack + ' &gt; Состояние и оплата заказа';

	boxClear();
	$.colorbox({ href: 'shop/order_check/' + iId + '/' + sPage, title: sTitle, width: '710px', maxHeight: '450px' });
}

function orderCancel(iId) {
	if (window.confirm('Вы уверены, что хотите отменить заказ?'))
		$.ajax({
			url: $('base').attr('href') + 'shop/order_cancel/' + iId + '/',
			cache: false,
			success: function() {
				cabinet('orders');
			}
		});
}

function player(sObjId, sFile, sImg, sYoutube, iWidth, iHeight) {
	var iWidth = (iWidth == undefined) ? 600 : iWidth;
	var iHeight = (iHeight == undefined) ? 450 : iHeight;
	var oOptions = {
		flashplayer:	'/plugins/jwplayer/player.swf',
		skin:			'/plugins/jwplayer/glow/glow.xml',
		width:			iWidth,
		height:			iHeight
	}

	if (sYoutube != undefined) {
		oOptions.file = sYoutube;
		oOptions.provider = 'youtube';
	} else {
		oOptions.file = '/images/video/' + sFile;
		oOptions.image = '/images/video/' + sImg;
	}

	jwplayer(sObjId).setup(oOptions);
}*/

function reflections(sSel) {
	var oOptions = {
		el: sSel,
		height: 0.3,
		opacity: 0.3,
		distanceV: 1,
		IEbackground: 'blue'
	}

	reflection(oOptions);
}

function slidesInit() {
	var sSel = '#slides',
		oSlideItem = $(sSel);

	oSlideItems = oSlideItem.children('img');
	iSlideCount = oSlideItems.length;
	iSlidePageWidth = 24;
	iSlideWidth = 433;
	iSlideSpace = 19;
	iSlideAnim = 200;
	iSlideTime = 4000;
	iSlide = 0;

	oSlideItem.append('<div id="points"></div>');
	var oSlidePagin = $('#points');

	oSlideItems.each(function(i) {
		oSlidePagin.append('<span' + ((i == 0) ? ' class="act"' : '') + '></span>');
	});

	oSlidePages = oSlidePagin.children('span');
	iSlidePagesWidth = oSlidePages.length * iSlidePageWidth;
	iSlidePagesWidth = (iSlidePagesWidth > iSlideWidth) ? iSlideWidth : iSlidePagesWidth;
	oSlidePagin.css('width', iSlidePagesWidth);

	oSlidePages.each(function(i) {
		$(this).mouseover(function() {
			slideShow(i);
		});
	});

	oSlideItem.mouseleave(
		function() {
			slideShow(iSlide, true);
		}
	);

	oSlideItem.show();
	reflections(sSel + ' > img');
	oSlideItems = oSlideItem.children('span');

	slideShow();
}

function slideShow(iId, bPlay) {
	if (top.intSlides != undefined) {
		oSlideItems.stop(true, true);
		clearInterval(intSlides);
	}

	if (iId == undefined || bPlay) {
		slidePage(iSlide);

		if (iId == undefined)
			oSlideItems.each(function(i) {
				$(this).css('left', (-iSlideWidth * (i + 1) + iSlideWidth - iSlideSpace * i + iSlideSpace) + 'px');
			});
		else {
			var aSlideIndex = [],
				aSlideLeft = [],
				iSlideLeft = oSlideItems.eq(iSlide).css('left');

			iSlideLeft = Number(iSlideLeft.substring(0, iSlideLeft.length - 2));

			oSlideItems.each(function(i) {
				aSlideLeft.push($(this).css('left'));
				aSlideLeft[i] = Number(aSlideLeft[i].substring(0, aSlideLeft[i].length - 2));

				aSlideIndex.push(i);
			});

			for (var i = aSlideLeft.length - 1; i >= 0; i--)
				if (aSlideLeft[i] > iSlideLeft)
					oSlideItems.eq(aSlideIndex[i]).css('left', '-=' + (iSlideWidth * iSlideCount + iSlideSpace * iSlideCount));
		}

		intSlides = setInterval(function() {
			oSlideItems.each(function(i) {
				$(this).animate({ left: '+=' + (iSlideWidth + iSlideSpace) }, iSlideAnim, function() {
					if (i == iSlideCount - 1) {
						oSlideItems.eq(iSlide).css('left', (-iSlideWidth * (iSlideCount - 1) - iSlideSpace * (iSlideCount - 1) + iSlideSpace) + 'px');
						iSlide = (iSlide < iSlideCount - 1) ? iSlide + 1 : 0;
						slidePage(iSlide);
					}
				});
			});
		}, iSlideTime);
	} else {
		iSlide = iId;
		slidePage(iSlide);

		var iPos = oSlideItems.eq(iSlide).css('left');
		iPos = Number(iPos.substring(0, iPos.length - 2)) - iSlideSpace;

		oSlideItems.each(function() {
			$(this).animate({ left: '-=' + iPos }, iSlideAnim);
		});
	}
}

function slidePage(iId) {
	oSlidePages.removeClass('act');
	oSlidePages.eq(iId).addClass('act');
}
