$(document).ready(function() {


	////// CLASSICS //////
	$('a.new-window').click(function(){
		window.open(this.href);
		return false;
	});


	////// KONSEPTI //////

	bindMenu();
	bindDetail();
	bindList();
        bindModalFilter();
	CoolHelper.updateFilterFromJSON();


	masonryDivs = $('.designers #content, .partners #content, .manufacturers #content');
	if(masonryDivs.find('.box').length > 0)
	{
		masonryDivs.masonry({
			singleMode: true,
			itemSelector: '.box'
		});
	}

	// INFO SECTION
	var userHeight = $(window).height();
	$('.info-bg').css('height', userHeight+'px');

	// PRODUCTS HOVER
	bindProductsHover();

	$('a.addProduct').click(function(e){
		$('#choosen-products').load(base_web_dir+lang+"/ajaxed/add-product/", {
			id:$(this).attr('id').replace("p", "")
		});
	});

	$('#product-contact').live('click',function(){
		var cm=$('#contactMail');
		if(cm.is(':visible')){
			cm.fadeOut();
		}else{
			cm.fadeIn();
		}
		return false;
	});
	activateForm();

	// PRODUCTS ADD LIGHTBOX
	$(".product-item .lightbox").hover(
		function () {
			$(this).parents('.product-info-holder').css("background", "url("+base_web_dir+"images/bg-png-50.png)");
			$("img", this).attr("src", base_web_dir+"images/ico-product-add-hover.png")

			$(this).prevAll('h3, p.meta').hide();
			$("p", this).show();

		},
		function () {
			$(this).parents('.product-info-holder').css("background", "url("+base_web_dir+"images/bg-png-10.png)");
			$("img", this).attr("src", base_web_dir+"images/ico-product-add.png")

			$(this).prevAll('h3, p.meta').show();
			$("p", this).hide();

		}
		);

	// Modal product filters
	$().makeModalFilter('#maker h4', lang+'/ajaxed/filter-manufacturers/');
	$().makeModalFilter('#designer h4', lang+'/ajaxed/filter-designers/');
        var
            form=$('#toolbar form'),
            find=$('#find');
        form.submit(function(){
            find.blur();
            if(find.val()==find.data('value')){
                CoolHelper.setTitle('');
                $('#find-filter').hide();
            }else{
                CoolHelper.setTitle(find.val());
                find.val(find.data('value'));
            }
            executeModalFilterSelection();
            return false;
        });
        if(find.length){
            find
                .data('value',find.val())
                .focus(function(){
                    if($(this).val()==$(this).data('value')){
                        $(this).val('');
                    }
                }).blur(function(){
                    if($.trim($(this).val())==''){
                        $(this).val($(this).data('value'));
                    }
                });
            $('#find-button').click(function(){
                form.submit();
            });
            $('#find-cancel').click(function(){
                CoolHelper.setTitle('');
                $('#find-filter').hide();
                executeModalFilterSelection();
            });
        }

        // VERY AWFUL IE JQUERY OPACITY BUG
        $('.box .holder-bg,.employee .info-holder').animate({opacity:.1},0);
        $('.news-item div.news-bg-holder').animate({opacity:.05},0);
        $('.news-1 div.news-bg-holder,.news-1 img').animate({opacity:.8},0);
        $('.news-2 div.news-bg-holder,.news-2 img').animate({opacity:.75},0);
        $('.news-3 div.news-bg-holder,.news-3 img').animate({opacity:.7},0);
        $('.news-4 div.news-bg-holder,.news-4 img').animate({opacity:.65},0);
        $('.news-5 div.news-bg-holder,.news-5 img').animate({opacity:.60},0);
        $('.news-6 div.news-bg-holder,.news-6 img').animate({opacity:.55},0);
        $('.news-7 div.news-bg-holder,.news-7 img').animate({opacity:.50},0);
        $('.news-8 div.news-bg-holder,.news-8 img').animate({opacity:.45},0);
        $('.news-9 div.news-bg-holder,.news-9 img').animate({opacity:.40},0);
        $('.news-10 div.news-bg-holder,.news-10 img').animate({opacity:.35},0);
		$('.news-11 div.news-bg-holder,.news-11 img').animate({opacity:.30},0);
		$('.news-12 div.news-bg-holder,.news-12 img').animate({opacity:.25},0);
		$('.news-13 div.news-bg-holder,.news-13 img').animate({opacity:.20},0);
		$('.news-14 div.news-bg-holder,.news-14 img').animate({opacity:.15},0);
		$('.news-15 div.news-bg-holder,.news-15 img').animate({opacity:.10},0);
		$('.news-16 div.news-bg-holder,.news-16 img').animate({opacity:.05},0);

	// EMPLOYEES HOVER
	$(".employee").hover(
		function () {
			$('.info-holder', this).stop().animate({
				opacity:.2
			},250);
			$('img.color', this).show();
			$('img.bw', this).hide();
		},
		function () {
			$('.info-holder', this).stop().animate({
				opacity:.1
			},250);
			$('img.bw', this).show();
			$('img.color', this).hide();
		}
		);

        // NEWS HOVER
	$(".news-item").hover(
		function () {
			this.prevOpacity = $(".news-bg-holder", this).css("opacity");
			$("div.news-bg-holder", this).stop().animate({
				opacity:.9
			},250);
			$("img", this).stop().animate({
				opacity:1
			},250);
		},
		function () {
			$("div.news-bg-holder", this).stop().animate({
				opacity: this.prevOpacity
			},250);
			$("img", this).stop().animate({
				opacity: this.prevOpacity
			},250);
		}
		);

	// MANUFACTURERS, PARTNERS HOVER
	//bindBoxHover();


	// EVENTS
	$().eventGallery();

	/*// HISTORY
	$.historyInit(callHistory);*/

	$(window).hashchange(function() {callHistory()});
    callHistory();

    // IE6 FIXY
    if($.browser.msie && $.browser.version==6){
        var
            logo=$('h1'),
            menu=$('#menu'),
            toolbar=$('#toolbar');
        toolbar.css({
            backgroundImage:'none',
            backgroundColor:'#313131',
            opacity:.9
        });
        $(window).scroll(function(){
            logo.css('top',$(this).scrollTop()+$(this).height()-logo.height()+'px');
            menu.css('top',$(this).scrollTop()+'px');
            toolbar.css('top',$(this).scrollTop()+'px');
            $('#modal-filter').css('top',$(window).scrollTop()+'px');
        });
    }

});

jQuery.fn.eventGallery = function(){
	$(".event-gallery a").click(function () {

		superParent = $(this).parents('.event-item');

		// Reset gallery
		$('.big-image', superParent).hide();
		$('.medium-image', superParent).fadeIn();

		// Init vars
		var mediumPhotoHref = $(this).attr("href");
		var bigPhotoHref = mediumPhotoHref.replace('m_', 'l_');
		var photoMeta = $(this).attr('class').match(/([0-9]+)-([0-9]+)/);
		var photoHeight = photoMeta[1];
		var photoWidth = photoMeta[2];

		$('.photo-holder a', superParent).attr("href", bigPhotoHref);
		$('.medium-image', superParent).attr("src", mediumPhotoHref);
		$('.big-image', superParent).attr({
			'src':bigPhotoHref,
			'height':photoHeight,
			'width':photoWidth
		});

		if((photoHeight < 550) && (photoWidth < 550)){
			$('.photo-holder a', superParent).addClass('no-resize').css("cursor", "auto");
		}else{
			$('.photo-holder a', superParent).removeClass('no-resize').css("cursor", "url("+base_web_dir+"images/cur-plus.cur), url(cur-plus.cur), auto");
		}

		$('.event-gallery span', superParent).hide();
		$("span", this).show();

		return false;
	});
	$(".photo-holder a").unbind();
	$(".photo-holder a").click(function (e) {
		if($(this).is('.no-resize')){
			return false;
		}

		superParent = $(this).parents('.event-item');

		//var photoMeta = $(this).attr('class').match(/([0-9]+)-([0-9]+)/);
		var photoHeight = $('.big-image', superParent).attr('height');
		var photoWidth = $('.photo-holder .big-image', superParent).attr('width');
		var offset = superParent.offset();
		var ratioX = (photoWidth-550)/550;
		var ratioY = (photoHeight-550)/550;
		var mouseX = (e.pageX-offset.left);
		var mouseY = (e.pageY-offset.top);

		$('.big-image', superParent).css({
			'top':(-(mouseY*ratioY)),
			'left':(-(mouseX*ratioX))
		}).fadeIn();
		$('.photo-holder .medium-image', superParent).fadeOut();

		$(".photo-holder").mousemove(function(e){
			var mouseX = (e.pageX-offset.left);
			var mouseY = (e.pageY-offset.top);
			// Image moving
			$('.photo-holder .big-image', superParent).css({
				'top':(-(mouseY*ratioY)),
				'left':(-(mouseX*ratioX))
			});
		});

		$('.big-image').click(function(){
			$('.photo-holder .big-image', superParent).fadeOut();
			$('.photo-holder .medium-image', superParent).fadeIn();
			return false;
		});

		return false;
	});
}

jQuery.fn.makeModalFilter = function(thisH4, ajaxFile){
	$(thisH4).click(function(){

		//RESET
		hideModal();

		// RENDER
		//$("#toolbar a").click(function(){
		//	return false;
		//});
		if($.browser.msie){
                    $('#content').css('position','static'); // SWITCH TO POSITION STATIC DUE TO Z-INDEX BUG
                    $("#toolbar").before('<div id="modal-holder"></div>');
                }else{
                    $("body").append('<div id="modal-holder"></div>');
                }
		$("#modal-holder").css({
			'width': $(window).width(),
			'height': $(document).height()
		});
		$("#toolbar").css("background", "#141511").css('opacity',1);
		$("#toolbar p, #toolbar a, #toolbar h4, #maker-cancel, #designer-cancel").css("color", "#3c3d38");
                $("#find,#find-button,#find-filter").css('opacity','0.2');


		$(this).parent('div').css("background", "#000");
		$(this).css("color", "#afde0d");
		$('#maker-cancel, #designer-cancel',$(this).parent()).css("color", "#afde0d");
		$("a", this).css("color", "#FFF");

		$('#modal-holder').click(function() {
			hideModal();
		});

		var posX = $(this).parent('div').offset().left;
		$("body").append('<div id="modal-filter"></div>');
		$('#modal-filter').css("left", posX+"px");

		$("#modal-filter").load(base_web_dir + ajaxFile, function(){

			$('div#modal-filter ul#alphabet li a').click(function(){

				if($(this).attr('id') != '') {

					$('div#modal-filter #modalList').load(base_web_dir + ajaxFile, {
						letter: $(this).attr('id'),
						filter: true
					}, bindModalFilter);

				} else {
					CoolHelper.setDesigner('');
					$('div#designer span:first').html('('+allDesigners+')');
					hideModal();
				}

				return false;
			});
			// Close
			bindModalFilter();


		});
		return false;
	});
}

function bindMenu(){
	$('#product-categories a').click(function() {
		if($(this).parents('li').eq(0).not('.selected').length == 1){
			CoolHelper.setCategory($(this).parents('li').eq(0).attr('id'));
                        $('#product-categories li').removeClass('selected');
                        $(this).parent().addClass('selected');
		}
                $.locationHash(CoolHelper.getLinkFilterPart());
		return false;
	});

}



function bindList() {
	$('div#BigProductsDiv .product-item a').click(function() {
		var link=this.href;
		var niceLink = link.match('([^\/]+\/){'+(3+(location.host=='localhost'))+'}(.*/)')[2];
                $.locationHash(niceLink); // pridat pokud budem chtit posilat i s filtrem  '/'+CoolHelper.getLinkFilterPart();
		return false;
	});



	$('div.pagination a').click(function() {
		page=$(this).attr('href').match(/n\.pagenumber=(\d+)/)[1];
		CoolHelper.pagination = page;
                $.locationHash(CoolHelper.getLinkFilterPart());
		return false;
	});
}

function bindModalFilter() {
	$('a#resetDesigner,#designer-cancel').click(function() {
		CoolHelper.setDesigner('');
		return executeModalFilterSelection();
	});

	$('a#all-manufacturers, #maker-cancel').click(function() {
		CoolHelper.setManufacturer('');
		return executeModalFilterSelection();
	});

	$('div#modal-filter #modalList a').not('#resetDesigner').click(function(){

		UlClass = $('div#modal-filter #modalList').attr('class');
		if(UlClass == 'designersUl') {
			CoolHelper.setDesigner($(this).attr('id'));
		} else if(UlClass == 'manufacturersUl') {
			CoolHelper.setManufacturer($(this).attr('id'));
		}

		return executeModalFilterSelection();
	});
}

function executeModalFilterSelection(){
	hideModal();
	CoolHelper.filterNeedsUpdate = true;
        $.locationHash(CoolHelper.getLinkFilterPart());
	return false;
}

function bindDetail() {

	$('#nextProduct,#prevProduct').click(function() {
		var link=this.href;
		var niceLink = link.match('([^\/]+\/){'+(3+(location.host=='localhost'))+'}(.*/)')[2];
                $.locationHash(niceLink);
		return false;
	});

	bindGallery();
}

function hideModal() {
	$('#modal-holder').remove();
	$('#modal-filter').remove();

	$("#toolbar, #toolbar div, #toolbar p, #toolbar a, #toolbar h4").attr("style", "");
        $('#maker-cancel, #designer-cancel').css("color", "#afde0d");
        $("#find,#find-button,#find-filter").css('opacity','1');
        if($.browser.msie){
            $('#content').css('position','relative'); // BACK TO RELATIVE
        }
}

function bindGallery() {
	$("#gallery a").click(function () {

		// Reset gallery
		$('#photo-holder #big-image').hide();
		$('#photo-holder #medium-image').fadeIn();

		// Init vars
		var mediumPhotoHref = $(this).attr("href");
		var bigPhotoHref = mediumPhotoHref.replace('m_', 'l_');
		var photoMeta = $(this).attr('class').match(/([0-9]+)-([0-9]+)/);
		var photoHeight = photoMeta[1];
		var photoWidth = photoMeta[2];

		$('#photo-holder a').attr("href", bigPhotoHref);
		$('#photo-holder #medium-image').attr("src", mediumPhotoHref);
		$('#photo-holder #big-image').attr({
			'src':bigPhotoHref,
			'height':photoHeight,
			'width':photoWidth
		});

		if((photoHeight < 550) && (photoWidth < 550)){
			$('#photo-holder a').addClass('no-resize').css("cursor", "auto");
		}else{
			$('#photo-holder a').removeClass('no-resize').css("cursor", "url("+base_web_dir+"images/cur-plus.cur), url(cur-plus.cur), auto");
		}

		$('#gallery span').hide();
		$("span", this).show();

		return false;
	});
	$("#photo-holder a").unbind();
	$("#photo-holder a").click(function (e) {
		if($(this).is('.no-resize')){
			return false;
		}

		//var photoMeta = $(this).attr('class').match(/([0-9]+)-([0-9]+)/);
		var photoHeight = $('#photo-holder #big-image').attr('height');
		var photoWidth = $('#photo-holder #big-image').attr('width');

		var offset = $('#photo-holder').offset();
		var ratioX = (photoWidth-550)/550;
		var ratioY = (photoHeight-550)/550;
		var mouseX = (e.pageX-offset.left);
		var mouseY = (e.pageY-offset.top);

		$('#photo-holder #big-image').css({
			'top':(-(mouseY*ratioY)),
			'left':(-(mouseX*ratioX))
		}).fadeIn();
		$('#photo-holder #medium-image').fadeOut();

		$("#photo-holder").mousemove(function(e){
			var mouseX = (e.pageX-offset.left);
			var mouseY = (e.pageY-offset.top);
			// Image moving
			$('#photo-holder #big-image').css({
				'top':(-(mouseY*ratioY)),
				'left':(-(mouseX*ratioX))
			});
		});

		$('#big-image').click(function(){
			$('#photo-holder #big-image').fadeOut();
			$('#photo-holder #medium-image').fadeIn();
			return false;
		});

		return false;
	});
        if($.browser.msie && $.browser.version==6){ // IE6 WIDTH 100% BUG
            $('#product-detail #product-info #gallery a span').each(function(){
                $(this)
                    .width($(this).parent().width())
                    .css('opacity',0.62);
            });
        }
}

function bindProductsHover() {
        if($.browser.msie){
            if($.browser.version==6){
                $('.product-info-holder-bg').height($(this).height()); // very awful IE6 or jquery or wtf bug with height:100%;
            }
            $('.product-info-holder-bg').stop().animate({opacity:.1},0);  // another awful blinking fix for IE
        }
	$(".product-item").hover(
		function () {
			$('.product-info-holder-bg', this).stop().animate({
				opacity:.2
			},250);
		},
		function () {
			$('.product-info-holder-bg', this).stop().animate({
				opacity:.1
			},250);
		}
		);
}

function bindBoxHover() {
	$(".box").hover(
		function () {
			$('.holder-bg', this).stop().animate({
				opacity:.2
			},250);
		},
		function () {
			$('.holder-bg', this).stop().animate({
				opacity:.1
			},250);
		}
		);
}

function activateForm(){
	var cm=$('#contactMail');
	$('div:eq(0)',cm).append('<input type="hidden" name="jsEnabled" value="1"/>');
	if(typeof(checkForm)!='undefined'){
		$('form')
			.submit(checkForm.checkForm)
			.find(checkForm.fieldSelector)
			.blur(checkForm.checkField)
			.change(checkForm.checkField)
			.end()
			.find("input[type='text'],input[type='password']")
			.keyup(checkForm.checkFieldWithTimeout)
		;
	}
}
function callHistory() {
        var
            hash=location.href.split('#')[1] || '',  // IE6 neumi location.hash kdyz je tam otaznik, resp. umi, ale dela s tim nejaky divny veci
            params=hash.split(/[\?&]/),
            allowedParams={
                'n.pagenumber':'pagination',
                'title':'title'
            }
		;
        if(lang == 'cs') {
		prodLink = 'cs/produkty/';
		konseptiTitle = " - Konsepti.cz — Inside of Life";
		}
		else if(lang == 'sk')
		{
		prodLink = 'sk/produkty/';
		konseptiTitle = " - Konsepti.sk — Inside of Life";
	} else {
		prodLink = 'en/products/';
		konseptiTitle = " - Konsepti.cz — Inside of Life";
	}
	if(hash == ''){ // TADY TO BYLO NEJAK PODIVNE, NEVIM JAK TO MOHLO FUNGOVAT, JESTLI TO TEDA VUBEC FUNGOVALO, TEDA ALESPON TAK JAK SI PREDSTAVUJU ZE BY TO FUNGOVAT MELO
            var loc=location.href.split(prodLink);
            if(loc.length>1){
                hash=loc[1].replace('#',''); // TEN REMOVE HASH TAM JE KVULI IE, VRACI TO TROCHU NEJAK JINAK
            }
	}
        if(CoolHelper.lastHash == hash){ // ZAMEZENI DVOJNASOBNYHO VOLANI SE STEJNEJMA PARAMETRAMA, NORMALNE SE TO NACITALO DYCKY DVAKRAT PO SOBE NEVIM VUBEC PROC
            return;
        }
	CoolHelper.lastHash = hash;

        var i,param;
        for(a in allowedParams){
            CoolHelper[allowedParams[a]]='';
        }
        for(i=1;i<params.length;i+=1){
            param=params[i].split('=');
            if(typeof(allowedParams[param[0]])!='undefined'){
                CoolHelper[allowedParams[param[0]]]=decodeURI(param[1]);
            }
        }
	if(typeof(pageTracker) != 'undefined'){
		pageTracker._trackPageview(base_web_dir+prodLink+hash);
	}
	if(typeof(pageTracker2) != 'undefined'){
		pageTracker2._trackPageview(base_web_dir+prodLink+hash);
	}
	var link=base_web_dir+prodLink+hash;
	link=link.replace(/\?keepEvents=1/,''); // odstraneni keepEvents
	$('div#BigProductsDiv').load(link, {
		ajax: 1
	}, function(){
		CoolHelper.setCallbacks();
		activateForm();
		/* PROC JE TO TADY A NE V COOLHELPERU? DAL JSEM TO TAM, TADY JE TO ZAVISLY NA ZAKLIKNUTY KATEGORII, A CO KDYZ NA NI NIKDO NEKLIKNUL A JEN ZMENIL HASH V URL NEBO KLIKNUL NA LINK?!
                 if(CoolHelper.category != null && CoolHelper.category != '') {
			$('#product-categories li').removeClass('selected');
			$('#product-categories li#'+CoolHelper.category).addClass('selected');
		} else {
			$('#product-categories li').removeClass('selected');
			$('#product-categories li').eq(0).addClass('selected');
		}*/
//		if(CoolHelper.filterNeedsUpdate == true){
                CoolHelper.updateFilterFromJSON();
			//CoolHelper.filterNeedsUpdate = false; // JEN AT SE TO RADSI PEKNE UPDATUJE PO KAZDY ZMENE HASHE
//		}
		document.title = customTitle + konseptiTitle;
	});

}