var oldValues = [];
var arrElements = ['fm-login','fm-password', 'login'];

function InitClear()
{
	var i = 0;
	var element = null
	for(i=0; i<arrElements.length; i++)
	{
		$('#'+arrElements[i]).each( function(j) { oldValues[i] = this.value } );
		$('#'+arrElements[i]).focus( fmOnFocus );
		$('#'+arrElements[i]).blur( fmOutFocus );
	}
}

function fmOnFocus()
{
	for(i=0; i<arrElements.length; i++)
	{
		if(this.id == arrElements[i])
		{
			if(oldValues[i] == this.value)
				this.value = "";
		}
	}
}

function fmOutFocus()
{
	for(i=0; i<arrElements.length; i++)
	{
		if(this.id == arrElements[i])
			if(!this.value || this.value == "")
				this.value = oldValues[i];
	}
}


function changeMenuSections()
{
	if($('.jsMenuSections').is('ul'))
	{
		$('.jsInvisible').hide();
		
		if($('.jsRecenzjeBody').is('body'))
		{	
			$('.jsRecenzjeSection').show();
			$('.jsMenuSections li').removeClass('active');
			$('.jsMenuSections .jsRecenzje').parent('li').addClass('active');
		}
		else
		{
			$('.jsInvisible:first').show();	
		}


		
		
		$('.jsMenuSections a').click(
			function()
			{		

				
				var liParent = $(this).parent('li');
				var aClass = $(this).attr('class');
				
				$('.jsMenuSections li').removeClass('active');
				$('.jsInvisible').hide();
				$('body').removeClass('best');
				
				$(liParent).addClass('active');
				$('.'+aClass+'Section').show();
				
// 				alert(aClass);
				
				if(aClass == 'jsPolecamy' || aClass == 'jsZapowiedzi' || aClass == 'jsTop10')
				{
// 					alert('nckjls');
					$('body').addClass('best');
				}

				
				return false;
			}
		
		);	
	}
	
}


function koszykParsePrice(price)
{
	if(!price)
		price = '0';
		
	var parsedPrice = 0.0;
	price = price.replace(',','.');
	price = price.replace(/[^0-9\.]/i,'');
// 	alert(price);
	parsedPrice = parseFloat(price);
	return parsedPrice;
	
}

function koszykReparsePrice(price)
{
	price = price.toFixed(2);
	var reparsedPrice = price.toString();
	
// 	x = reparsedPrice.split('.');
// 	x1 = x[0];
// 	x2 = x.length > 1 ? ' ' + x[1] : '';
// 	var rgx = /(\d+)(\d{3})/;
// 	while (rgx.test(x1)) {
// 		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
// 	}
	
// 	reparsedPrice =  x1 + x2;
	reparsedPrice = reparsedPrice.replace('.',',');
	return reparsedPrice;
}

function initCenaDelivery()
{

	$('.jsPrzesylkaCena').hide();
	var labelClass = $('.jsDostawa label input[@checked]').parent('label').attr('class');
	$('.'+labelClass+'Val').show();
// 	alert('.'+labelClass+'Val');
	
	var podSuma = koszykParsePrice($('span.jsKoszykPodsuma').text());
	var Suma = koszykParsePrice($('span.jsKoszykSuma').text());
	var Rabat = koszykParsePrice($('span.jsKoszykRabat').text());
	var Przesylka = koszykParsePrice($('.'+labelClass+'Val span.jsKoszykPrzesylka').text());
	
	Suma = podSuma + Przesylka;
// 	alert(Suma+' '+Rabat);
	Suma = Math.round((Suma - Rabat)*100)/100;
	
// 	alert(Suma+' '+Rabat);
	$('span.jsKoszykSuma').text(koszykReparsePrice(Suma));
	
}

function changeCenaDelivery()
{
	
	if($('.jsDostawa').is('td'))
	{
		initCenaDelivery();
		$('.jsDostawa label input').click(
			function()
			{
				initCenaDelivery();
				return true;
			}
		);
	}
	
	
}

function changeAdresBox()
{

	$('.jsAdresBox').hide();

	var inpVal = $('.jsAdres[@checked]').val();
	
	if(inpVal == 1)
	{
		$('.jsAdresBox').show();
		
	}
	else
	{
		$('.jsAdresBox').hide();
	}

}

function initAdresBox()
{
	if($('.jsAdres').is('input'))
	{
		changeAdresBox();
	
		$('.jsAdres').change(
			function()
			{	
				changeAdresBox();
			}
		);
	}
}

function zaznaczWszystkie()
{
	if($('.jsZaznaczWszystkie').is('label'))
	{
	
	
// 	$($('.jsZaznaczBox input:checkbox').get(0)).css({ backgroundColor:"yellow", fontWeight:"bolder" });
	
		$('.jsZaznaczWszystkie input').click(changeCheckboxesVal);
		
		$('.jsZaznaczWszystkie a').click(changeCheckboxesVal);
	}

}

function changeCheckboxesVal()
{

	$('.jsZaznaczBox input:checkbox').each(
		function(i)
		{
			if($($('.jsZaznaczBox input:checkbox').get(i)).attr('checked'))
			{
				$('.jsZaznaczBox input:checkbox').removeAttr('checked');	
				$('.jsZaznaczWszystkie a').text('Zaznacz wszystkie');

								$('.jsZaznaczWszystkie input:checkbox').removeAttr('checked');
				return false;			
			}
			else
			{
				$('.jsZaznaczBox input:checkbox').attr('checked','checked');
				$('.jsZaznaczWszystkie a').text('Odznacz wszystkie');
				$('.jsZaznaczWszystkie input:checkbox').attr('checked','checked');
				return false;
			}
		}
	);

}

function setUserType()
{
	if($('.jsUserType').is('label'))
	{
	
		changeUserType();
		$('.jsUserType input').change(
			function()
			{
				changeUserType();
				return true;
			}
		);
			
	
	}
}

function changeUserType()
{
	$('.jsCompanyFields').hide();
	var userType = $('.jsUserType input[@checked]').val();
	
	if(userType == 'firma')
	{	
		$('.jsCompanyFields').show();	
		$('label[for=reg-password]').hide();
		$('label[for=reg-password_verify]').hide();
		
		
	// 	dla zamawiania
		$('.jsName span:nth-child(2)').text("Imię");
		$('.jsSurname span:nth-child(2)').text("Nazwisko");
		$('.jsFirma span:nth-child(2)').text("Nazwa firmy *");
		$('.jsNip span:nth-child(2)').text("Nip *");
	}
	else
	{
		$('.jsCompanyFields').hide();
		$('label[for=reg-password]').show();
		$('label[for=reg-password_verify]').show();

// 		dla zamawiania
		$('.jsName span:nth-child(2)').text("Imię *");
		$('.jsSurname span:nth-child(2)').text("Nazwisko *");
		$('.jsFirma span:nth-child(2)').text("Nazwa firmy");
		$('.jsNip span:nth-child(2)').text("Nip");
	}

}


var origScroll = 0;

function initLoginBox(parentToClick)
{
	if($('#login').is('div'))
		return false;
		
	$divLogin = $('#loginInvisible');
	$divLogin
		.before('<iframe id="TB_HideSelect"></iframe><div id="TB_overlay" class="TB_overlayBG"></div>')
		.show()
		.attr('id', 'login');
	
	
	if(typeof document.body.style.maxHeight === "undefined")
	{
		$("body","html").css({height: "100%", width: "100%"});
		$("html").css("overflow","hidden");
		$('html').animate({scrollTop: 0}, 20);
	}
	
	$('#TB_overlay').click(closeLoginBox);
	
	if($divLogin.hasClass('loginInitialized'))
		return true;
	
	$divLogin.addClass('loginInitialized');
	
	$('a.zamknij', $divLogin).click(
		closeLoginBox
	);
	
	$('form', $divLogin).submit(
		function()
		{
			$.post(
				'index.php?JSONLogin',
				{
					'fm-email': $('#fm-email').val(), 
					'fm-password': $('#fm-password').val(), 
					'fm-autologin': $('#fm-autologin').val()
				},
				function (resData)
				{
					if(parseInt(resData.loggedIn))
					{
						$(parentToClick).trigger('click', [1]);
						return false;
					} else {
						alert('Logowanie nie powiodło się.\nNiestety podałeś nieprawidłowe lub nieaktywne dane użytkownika.');
					}
				},
				'json'
			);
			return false;
		}
	);
	
}

function closeLoginBox()
{
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
		
	$divLogin = $('#login');
	$('#TB_overlay').fadeOut(500,
		function()
		{
			$('#TB_HideSelect').remove();
			$(this).remove();
		}
	);
	$divLogin.hide().attr('id', 'loginInvisible');
	return false;
}



function initLogin()
{
	$('.jsLogin').click(
		function(event, doNotEnterLogin)
		{
			if(!doNotEnterLogin)
			{
				initLoginBox(this);
				return false;
			} 
			if($(this).is('a'))
			{
				document.location.href = $(this).attr('href');
			}
			return true;
		}
	);
}

function hideNewsletterSection()
{
	$('.jsNewsletterSection').hide();
	
	var inpVal = $('.jsNewsletterOnOff input[@checked]').val();
	
	if(inpVal == 1)
	{
		$('.jsNewsletterSection').show();
	}
	else
	{
		$('.jsNewsletterSection').hide();
	}
	
}

function initNewsletterSection()
{
	if($('.jsNewsletterOnOff').is('label'))
	{
		hideNewsletterSection();
		
		$('.jsNewsletterOnOff input').click(hideNewsletterSection);
		
	}
}


function initCalendar()
{
	$tableCalendar = $('table.jsCalendar');
	if(!$tableCalendar.is('table'))
		return false;
		
	// init switch month
	
	$selectSwitch = $('select#jsSwitchMonth');
	$selectSwitch.change(
		function()
		{
			var currValue = $selectSwitch.val();
			var currYear = currValue.replace(/\|.*$/i, '');
			var currMonth = currValue.replace(/^.*\|/i, '');
			var currMonthDesc = currMonth.replace(/^.*\#/i,'');
			var currMonth = currMonth.replace(/^.*\|/i,'').replace(/\#.*$/i,'');
			
			calendarChangeMonth(currYear, currMonth, currMonthDesc);
			return true;
		}
	);
	
	// init hover day
	$('td>a')
		.css('cursor','default')
		.click(
		function()
		{
			return false;
		}
	);
	$('td>a, td', $tableCalendar).hover(
		function()
		{
			$td = $(this);
			if(!$(this).is('td'))
				$td = $(this).parents('td');
			if(!$('div.hover-wrapper', $td).is(':visible'))
			{
				$('div.hover-wrapper:visible', $tableCalendar).hide();
				$('div.hover-wrapper:hidden', $td).fadeIn(500);
			}
			return false;
		},
		function()
		{
			return true;
		}
	);
	
	$($tableCalendar).hover(
		function()
		{
			return true;
		},
		function()
		{
			$('div.hover-wrapper:visible', $tableCalendar).hide();
			return true;
		}
	);
	
}




function calendarChangeMonth(intY, intM, strM)
{
	$tableCalendar = $('table.jsCalendar');
	
	// change title
	$('#jsCalendarTitle').html('<span>'+intY+'</span> '+strM);
	
	// hide current
	$('tr.jsCalendarRow', $tableCalendar).hide();
	
	// display new
	$('tr.jsRowM'+intM, $tableCalendar).show();
}



function initNaviHover()
{
	$('#navi-menu li').hover(
		function()
		{
			$('>ul', this).show();
			$(this).addClass('active');
		},
		function()
		{
			$('>ul', this).hide();
			$(this).removeClass('active');
		}
	);
}


function defaultInputText($selector, tekst)
{
	if(!$selector.val())
		$selector.val(tekst);
		
	$selector.bind('focus',
		function()
		{
			if($selector.val() == tekst)
			{
				$selector.val('');
				return true;
			}
		}
	)
		.bind('blur',
		function()
		{
			if(!$selector.val())
			{
				$selector.val(tekst);
				return true;
			}
		}
	);
	
}


function initNapiszRecenzje()
{
	var $title = $('#dr-title');
	if(!$title.is('input'))
		return false;
		
	var tekst = 'Tytuł recenzji';
	defaultInputText($title, tekst);
	
	$title.parents('form').bind('submit',
		function()
		{
			if($title.val() == tekst || $title.val() == '')
			{
				alert('Musisz podać tytuł swojej recenzji.');
				$title.trigger('focus');
				return false;
			}
			return true;
		}
	);
}


function initWyszukiwarka()
{
	var $search = $('#szukaj input[type=text]');
	if(!$search.is('input'))
		return false;
		
	if($search.attr('id') == 'en-site-search')
	{
		var tekst = 'Search';
	} else {
		var tekst = 'Szukaj: wpisz tytuł, serię wydawniczą lub autora';
	}
	
	defaultInputText($search, tekst);
	
	$search.parents('form').bind('submit',
		function()
		{
			if($search.val() == tekst)
				$search.val('');
			return true;
		}
	);	
}

function submitRightsSoldForm()
{
	if($('#jsFormCountries').is('form'))
	{
		$('.jsSubmit').hide();
		
		$('select', 'form#jsFormCountries').change(
			function()
			{
				$('form#jsFormCountries').submit();
				return true;
			}
		);
	
	}
}


function initNajnowszaRecenzja()
{
	if(document.location.href.indexOf('#recenzja') == -1)
		return true;
		
	var idRec = document.location.href.replace(/^.*\#/i, '');
	
	var $rec = $('#'+idRec);
	var offset = $rec.offset();
	$('html').animate({ scrollTop: offset.top });
	
}


function initAutocomplete()
{

	$("#SiteSearch").autocomplete('search.php', {
		width: 400,
		multiple: true,
		matchContains: true,
		max: 30,
		cacheLength: 10
	}); 
}



function initPriceCss()
{
	$body = $('body');
	if(!$body.hasClass('jsWyrownajCeny'))
		return true;
		
	$('div#content div.polecane').each(
		function()
		{
			movePriceBoxes(this);			
		}
	);
	
	$('div#content div.polecane2').each(
		function()
		{
			movePriceBoxes(this);			
		}
	);
	
	$('#m2, #m5').click(
		function()
		{
			$('div#content div.polecane, div#content div.polecane2').each(
				function()
				{
					movePriceBoxes(this);			
				}
			);
		}
	);
	
}



function movePriceBoxes(parentNode)
{
	// znajdz max.
	var max = 0;
	
	$(parentNode).find('.pozycja-dane h4').css('height','auto');
	
	$('div.pozyja-wrapp', parentNode).each(
		function()
		{
			var divHeight = $('div.pozycja-dane', this).height();
// 			$('div.pozycja-bottom', this).append('<br /><i>'+divHeight+'</i><br />');
			if(divHeight > max)
				max = divHeight;
		}
	);
	
	$('div.pozyja-wrapp', parentNode).each(
		function()
		{
			var divHeight = $('div.pozycja-dane', this).height();
			var diff = max - divHeight;
			if(diff > 0)
			{
				if($.browser.msie && parseInt($.browser.version) < 8)
				{
					diff = diff - 4;
					if(!$(this).parents('div.polecane').is('div'))
						diff = diff - 2;
				}
					
				var h4Height = $('div.pozycja-dane h4', this).height();
				h4Height = h4Height + diff;
				$('div.pozycja-dane h4', this).height(h4Height);
// 				$('div.pozycja-bottom', this).append('<b>'+h4Height+'</b>');
			}
		}
	);
}


function specialOffersPagination()
{
	var $divPolecamy = $('body.MainPage .jsPolecamySection');
	
	if(!$divPolecamy.is('div'))
		return true;
		
	var $aPages = $('.pages a', $divPolecamy);
	$aPages.unbind('click.polecamy');
	
	$aPages.bind('click.polecamy',
		function()
		{
			var aHref = $(this).attr('href');
			var strPage = aHref.replace(/^.*page\=/,'');
			
			$.get(
				'index.php?mpoffer&ajax=1&page='+strPage,
				{
					mpoffer: 1,
					ajax: 1,
					page: strPage
				},
				function (retData)
				{
					$divPolecamy.html(retData);
					specialOffersPagination();
					return true;
				},
				'html'
			);
			
			return false;
		}
	);
	
}


/* init */
function initializeMain()
{
	InitClear();
	
//  nawigacja - hovery
	initNaviHover();

// 	strona glowna, produkt, autor	
	changeMenuSections();
	
// oferty specjalne na glownej - nawigacja/paginacja
	specialOffersPagination();
	
//	ceny na jednym poziomie
	initPriceCss();

// 	delivery
	changeCenaDelivery();
	
// 	rejestracja, edycja profilu - adres korespondencyjny
	initAdresBox();
	setUserType();
	
// 	rejestracja, edycja profilu
	initNewsletterSection();
	
// 	rejestracja, newsletter, edycja profilu
	zaznaczWszystkie();
	
//	logowanie
	initLogin();
	
//	kalendarz	
	initCalendar();
	
//	recenzja
	initNapiszRecenzje();	
	initWyszukiwarka();	
	
// 	rights sold
	submitRightsSoldForm();
	
	
//	najnowsza recenzja
	initNajnowszaRecenzja();
		
//	autocomplete
	initAutocomplete();
	
}


$(document).ready(initializeMain);
