
var defEasing = "easeInOutBack";

var rTime = new Date(1, 1, 200, 12,00,00);
var timeOut = false;
var delta = 200;

var backLoaded = false;
var currBackPoolCount = 0;
var backPoolFolder = "xl";
if(screen.width<=1900 && screen.width>1280)
{
	backPoolFolder = "l";
}
else if(screen.width<=1280)
{
	backPoolFolder = "m";
}
	
$(document).ready(function()
{
	//BlockUI defaults
	//$.blockUI.defaults.message = '<div class="loading_indicator">Loading…</div>';
	
	if(location.href.indexOf('module')!=-1)
	{
		//FirstSetBack();
	}
	
	
	$(window).resize(function(){
		rTime = new Date();
		if(timeOut==false)
		{
			timeOut = true;
			setTimeout(ResizeEnd, delta);
		}
	});
	
	$("#LoginButton").bind('click', function(e){
		//e.preventDefault();
		/*
if($("#LoginBox").not(":animated"))
		{
			if($("#LoginBox").height()==110)
			{
				$("#LoginBox").animate({
					'height': '0px'
				},500, defEasing);
				$("#LoginBox").fadeOut(200);
			}
			else
			{
				$("#LoginBox").fadeIn(200);
				$("#LoginBox").animate({
					'height': '110px'
				},500, defEasing);
			}
		}
*/
		
		var loginModalTitle = "Giriş";
		var loginModalNewMember = "Kayıt ol";
		var loginButton = "Giriş";
		var loginCancelButton = "İptal";
		
		var loginFailTitle = "Uyarı";
		var loginFailMessage = "Giriş başarısız!";
		var loginTryAgain = "Yeniden dene";
		
		var emailFailMessage = 'E-posta adresinizi doğru giriniz';
		var userNotExists = 'Bu e-posta ile kayıtlı kullanıcı yok.';
		
		var passResetTitle = "Şifre Yenileme";
		var passResetEmail = "E-posta adresiniz";
		var passResetSend = "Gönder";
		var passResetSuccessMessage = 'Size şifrenizi yenileyebilmeniz için gerekli kısayolu içeren bir e-posta gönderdik.';
		
		/*
if($("#LanguageEn").length==0)
		{
			loginModalTitle = "Login";
			loginModalNewMember = "Register";
			loginButton = "Login";
			loginCancelButton = "Cancel";
			loginFailTitle = "Error";
			loginFailMessage = "Login failed!";
			loginTryAgain = "Try again";
			passResetTitle = "Password Reset";
			passResetEmail = "E-mail address";
			passResetSend = "Send";
			passResetSuccessMessage = 'We have sent you en e-mail including link to reset your password.';
			emailFailMessage = 'E-mail address is in wrong format';
			userNotExists = 'No user associated with that e-mail.';
		}
*/
		
		new tor.modal({
			title: loginModalTitle,
			content: $('#LoginBox').html(),
			width: 325,
			buttons: [
			{
				title: loginButton,
				click: function(modal){
					emailBox = modal.modal.find('#LoginBoxEmail').val();
					passBox = modal.modal.find('#LoginBoxPass').val();
					
					if(emailBox.length>0 && passBox.length>0)
					{
						//modal.modal.block();
						$.ajax({
							url: '/action.php?do=do-login',
							type: 'POST',
							data: modal.modal.find('#loginBox').serialize(),
							success: function(res){
								if( res.success ){
									DoneLogin();
									$.unblockUI();
								}else{
									
									//LoginModal(res.message);
									new tor.modal({
										title: loginFailTitle,
										content: loginFailMessage,
										buttons: [{
											title: loginCancelButton,
											close: true
										},
										{
											title: loginTryAgain,
											click: function(){
												$("#LoginButton").trigger('click');
											}
										}]
									});
								}
							},
							dataType: 'json'
						});
					}
				}
			},
			{
				title: loginModalNewMember,
				cssclass: 'registerButton',
				click: function(){
					window.location = '/?module=register';
				}
			},
			{
				title: loginCancelButton,
				close: true
			}]
		});
		
		//Set ENTER keypress
		$(document).bind('keydown', function(e){
			if(e.keyCode==13)
			{
				$(".modalButtons:visible ul li:first a").trigger('click');
			}
		});
		
		$("#PasswordReset").live('click', function(){
			new tor.modal({
				title: passResetTitle,
				content: '<div class="errors"></div><div class="input-area">'+passResetEmail+': <input type="text" maxlength="50" class="email-field"></div>',
				width: 300,
				buttons: [{
					title: passResetSend,
					cssclass: 'Send',
					click: function(modalObj){
						emailValue = modalObj.modal.find('.email-field').val();
						errorContainer = modalObj.content.find('.errors');

						// validation
						if( emailValue < 6 || emailValue.indexOf('@') == -1 || emailValue.indexOf('.') == -1 ){
							if( errorContainer.find('.validation').length == 0 ){
								errorContainer.append('<div class="validation">'+emailFailMessage+'</div>');
							}
							return false;
						}

						modalObj.modal.block();
						errorContainer.empty();

						// ajax request
						$.ajax({
							url: '/action.php?do=password-reset',
							type: 'POST',
							data: {
								email: emailValue
							},
							success: function(response){
								modalObj.modal.unblock();

								if( response.success ){
									// done
									modalObj.content.html(passResetSuccessMessage);
									// change button
									modalObj.buttons.find('.Send').remove();
									modalObj.buttons.find('.Cancel').html('Tamam');
								}else{
									// show error
									if( errorContainer.find('.error').length == 0 ){
										errorContainer.append('<div class="error">'+userNotExists+'</div>');
									}
								}
							},
							dataType: 'json'
						});
					}
				},
				{
					title: loginCancelButton,
					cssclass: 'Cancel',
					close: true
				}]
			});
		});
		
	});
	
	/*
$("#loginBox").submit(function(e){
		e.preventDefault();
		
		if($("#LoginBoxEmail").val().length>0 && $("#LoginBoxPass").val().length>0)
		{
			$.ajax({
				url: 'action.php?do=do-login',
				type: 'POST',
				data: $(this).serialize(),
				success: function(res){
					if( res.success ){
						DoneLogin();
					}else{
						
						LoginModal(res.message);
					}
				},
				dataType: 'json'
			});
		}
	});
	
	$("#LoginModalClose").bind('mouseup', function(){
		$("#LoginModal").fadeOut(500);
	});
*/
	
	
	//Set random background from pool
	SetBackRandom();
	
	$("#LanguageEn").live('click', function(){
		//e.preventDefault();
		
		$.ajax({
			type: "POST",
			url: "action.php?do=set-language",
			data: "lang=en",
			success: function(res){
				window.location = res.backurl;
			}
		});
	});
	
	$("#LanguageTr").live('click', function(){
		//e.preventDefault();
		
		$.ajax({
			type: "POST",
			url: "action.php?do=set-language",
			data: "lang=tr",
			success: function(res){
				window.location = res.backurl;
			}
		});
	});
	
	
});

function DoneLogin()
{
	var currLang = "tr";
	/*
if($("#LanguageEn").length==0)
	{
		currLang = "en";
	}
*/
	$.ajax({
		url: 'action.php?do=main-navi&type=ajax&lang='+currLang+'',
		success: function(res){
			$('#Header').html("<a href='index.php'><img src='images/logo2.png' /></a>"+res);
			/*
$("#LoginBox").animate({
				'height': '0px'
			},500, defEasing);
			$("#LoginBox").fadeOut(200);
			if($("#CartBox .loading").is(":visible"))
			{
*/
				$("#CartBox .loading").css('display', 'none');
			//}
		}
	});
}

// Show Message overlaying login box
function LoginModal(msg)
{
	if($("#LoginBox").height()!=110)
	{
		$("#LoginBox").animate({
			'height': '110px'
		},500, defEasing);
	}
	$("#LoginModalContent").html(msg)
	$("#LoginModal").fadeIn(500);
	setTimeout('$("#LoginModal").fadeOut(500)', 3000);
}

// Set Random Background image
function SetBackRandom()
{
	var randomInt = Math.floor(Math.random()*15);
	if(currBackPoolCount == randomInt || randomInt == 0)
	{
		SetBackRandom();
	}
	else
	{
		$("#BackgroundImg").css("display", "none");
		$("#BackgroundImg").attr("src", "images/backpool/"+backPoolFolder+"/"+randomInt+".jpg");
		FirstSetBack();
		//SetBackPool();	
		currBackPoolCount = randomInt;
		
		//Set background image session by ajax
		/*
$.ajax({
			type: "POST",
			url: "action.php?do=set-backimg-session",
			data: "img="+backPoolFolder+"/"+randomInt+""
		});
*/
	}
	
}

function SetBackPool()
{
	var t = setInterval(function(){
		var randomInt = Math.floor(Math.random()*15);
		if(currBackPoolCount == randomInt || randomInt == 0)
		{
			clearInterval(t);
			SetBackPool();
		}
		else
		{
			
			$("#BackgroundImg").fadeOut(400, function(){
				$("#BackgroundImg").attr("src", "images/backpool/"+backPoolFolder+"/"+randomInt+".jpg");
				FirstSetBack();
			});
			
			//$(".box1Content").html($(".box1Content").html()+" - "+randomInt);
			currBackPoolCount = randomInt;	
		}
		
	},180000);
}

function FirstSetBack()
{
	var t = setInterval(function(){
		var backImg = $("#BackgroundImg");
		if(backImg[0].complete)
		{
			backLoaded = true;
		}
		if(backLoaded)
		{
			clearInterval(t);
			//$("#Background").fadeIn(400);
			ResizeEnd();
		}
	},200);
}

function ResizeEnd()
{
	if(new Date() - rTime < delta)
	{
		setTimeout(ResizeEnd, delta);
	}
	else
	{
		timeOut = false;
		if(window.innerWidth!=undefined)
		{
			var innerWidth = window.innerWidth;
			var innerHeight = window.innerHeight;
		}
		else
		{
			var innerWidth = document.documentElement.clientWidth;
			var innerHeight = document.documentElement.clientHeight;
		}
		
		var backImg = new Image();
		backImg.src = $("#BackgroundImg").attr('src');
		var imgWidth = backImg.width;
		var imgHeight = backImg.height;
		
		$("#BackgroundImg").fadeOut(150, function(){
			var targetWidth1 = (innerHeight*imgWidth)/imgHeight;
			if(targetWidth1<innerWidth)
			{
				var targetHeight1 = ((innerWidth+20)*imgHeight)/imgWidth;
				if(targetHeight1<innerHeight)
				{
					$("#BackgroundImg").css('height', innerHeight);
					$("#BackgroundImg").css('width', targetWidth1);
					var leftMinus = (targetWidth1-innerWidth)/2;
					$("#BackgroundImg").css('margin-left', -leftMinus);
					$("#BackgroundImg").css('margin-top', "0px");
					$("#BackgroundImg").fadeIn(300);
					
					$("#BackImgOverlay").css('height', innerHeight);
					$("#BackImgOverlay").css('width', targetWidth1);
					
				}
				$("#BackgroundImg").css('width', innerWidth+20);
				$("#BackgroundImg").css('margin-left', "-10px");
				$("#BackgroundImg").css('height', targetHeight1);
				$("#BackgroundImg").css('margin-top', "-"+((targetHeight1-innerHeight)/2)+"px");
				$("#BackgroundImg").fadeIn(300);
				
				$("#BackImgOverlay").css('height', targetHeight1);
				$("#BackImgOverlay").css('width', innerWidth+20);
			}
			else
			{
				$("#BackgroundImg").css('height', innerHeight);
				$("#BackgroundImg").css('width', targetWidth1);
				var leftMinus = (targetWidth1-innerWidth)/2;
				$("#BackgroundImg").css('margin-left', -leftMinus);
				$("#BackgroundImg").css('margin-top', "0px");
				$("#BackgroundImg").fadeIn(300);
				
				$("#BackImgOverlay").css('height', innerHeight);
				$("#BackImgOverlay").css('width', targetWidth1);
			}
		});
		
		//alert("screen h: "+innerHeight+" w: "+innerWidth+" - bg h: "+($("#BackgroundImg").css('height'))+" w: "+($("#BackgroundImg").css('width')));
		
	}
}


function GetCleanImgSrc(ele)
{
	var patt = /images\/backpool\/+[a-z].+.jpg/;
	var result = patt.exec(ele);
	
	//alert(result);
	
	return result;
}


function ElementAjaxLoad(ele)
{
	$(ele).append("<div class='blockBackFade' style='position:absolute; left:0px; top:0px; right:0px; bottom:0px; background-color:white; opacity:0.9; z-index:1000'><div class='ajaxLoading' style='position: absolute; z-index: 1010; left: 50%; margin-left: -24px; bottom: 20px;'><img src='images/ui/load_big.gif' /></div></div>")
}

function ElementAjaxLoaded(ele)
{
	$(".blockBackFade").remove();
}




















	
	
