// function setupTabs(){
// 	$('.tabs a, a[data-open-tab]').map(function(){
// 		var href = $(this).attr('href');
// 		
// 		$(this).attr('href',href.replace('#','#tab-'))
// 	})
// 	
// 	$('.tabs').tabs();
// 	
// 	$('.tabs').bind('change', function (e) {		// console.log($(e.target).attr('href'))
// 		var target = $($(e.target).attr('href'))
// 		target.filter('.columns').not('.done').addClass('done').columnize({columns:3});
// 		$('.column').removeAttr('style').addClass('span4');
// 		
// 		var hash = $(e.target).attr('href');
// 		
// 		document.location.hash = hash.replace('#tab-','#');
// 
// 		$(window).scrollTo(hash, 500,{
// 			offset:-120
// 		});
// 		return false;
// 	})
// 	
// 	$('a[data-open-tab]').click(function(){
// 		$('.tabs [href=' + $(this).attr('href') + ']').trigger('click');
// 		return false;
// 	})
// }

var cookie = $.cookie("popup");	
(function(){
    // remove layerX and layerY
    var all = $.event.props,
        len = all.length,
        res = [];
    while (len--) {
      var el = all[len];
      if (el != 'layerX' && el != 'layerY') res.push(el);
    }
    $.event.props = res;
}());

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}


$(document).ready(function(){	
	
	var space = $('#page-head').outerHeight() + $('header').outerHeight() + $('footer').outerHeight() + $('#quick-contact').outerHeight() + $('#menu').outerHeight() + parseInt($('#content').css('padding-top')) + parseInt($('#content').css('padding-bottom')) + 21;
	
	selectModel();
	popovers();
	sinfinCredit();
	$('#form_popup').live('submit', function(){
		toggleSubmitButton('hide');
	})
	
	$('#content').css({
		'min-height':$(window).height() - space
	})
	
	$('p').cstypo();
	
	// $('.price-format').formatCurrency($.extend({ colorize: true }, $.formatCurrency.region['cs-CE']));
	
	$('.price-format').formatCurrency({
		region: 'cs-CZ',
		roundToDecimalPlace: -2
	});
	
	// ie7 inline-block
	if ($.browser.msie && $.browser.version <= 7) {
		$('div, span, a, ul, li, p').filter(function(){
			return $(this).css('display') == 'inline-block';
		}).css({display:'inline', zoom:1});
	}
	
	if ($.browser.msie && $.browser.version == 8) {
		$('a[href=#tab-mapa]').live('click',function(){
			$('#tab-mapa').html($('#tab-mapa').html());
		})
	}
	
	$('.columns').find('h2, ul').not('.break').addClass('dontend');
	
	fixedMenu();
	popupCookie();
	
	$('.columns:visible').addClass('done').columnize({columns:3});
	$('.column').removeAttr('style').addClass('span4')
	
	sortingElements();
	gallery();
	// carousel();
	if($('#intro').length > 0) intro();
	form();
	
	$('#form_popup').click(function(event){
		event.stopPropagation('click', 'body', hidePopup);
	})

	
	$('a[data-close]').live('click', function(){
		$('#'+$(this).data('close')).hide();
		return false;
	})	
	
	$('.features li')
		.filter('.dynamic').map(function(){
			var $this = $(this);
			var text = $this.find('span.text');
			var offset = 3 + 1000/$this.width()//10;
			
			
			$this.append('<img src="/files/images/bullet.png" class="bullet" />')
		
			$this.css({
				height:$(this).width(),
				'margin-left':offset*.9,
				'margin-bottom':offset*1.2
			}).find('span.text').css({
				'margin-top': $this.height()/2 - text.height()/2,
				'width':$this.width()
			}).end().find('img').css({
				height:$this.width() + offset,
				height:$this.width() + offset,
				left: -offset/2,
				top: -offset/2
			})
		})
	$('.features').masonry({
		columnWidth:2
	})
	
	$('p, h1, h2, h3, h4, h5, strong, li').cstypo();
	
	$('a[data-em]').each(function(){
		e = $(this).data('em').replace('/','@');
		$(this).attr('href', 'mailto:'+e).not('.custom-text').text(e);
	});
	
	// $('form').submit(function(){
	// 	$(this).find('[type=submit]').hide();
	// })
	
	
	$('.row').map(function(){		
		if($(this).hasClass('bordered-top')){
			$(this).append('<hr class="span border border-top" />');
		} else if($(this).hasClass('bordered')){
			$(this).append('<hr class="span border" />');
		}
	})
})



var TO = false;
var winWidth;
var diff, diff2;

function resizeIntro() {
	diff = winWidth - $('#intro').width();	
	
	$('#intro img').animate({
		left : '+='+ (-diff/2)
	})

	winWidth = $('#intro').width();
}


function selectModel(){
	$('#select_model').change(function(){
		var val = $(this).val();
		if(val != ''){
			$('.sort .car').hide().filter('[data-model=' + val +']').show();
		}else{
			$('.sort .car').show();
		}
	})
}


$(window).load(function(){
	var hash = document.location.hash;
	if(hash != false){
		// alert(hash)
		if(hash == '#rezervace'){
			$('#rezervace').trigger('click');
		}else{
			hash = hash.replace('#','#tab-')
			document.location.has = '#';
			$('[href='+hash+']').trigger('click');
			return false;
		}
	}
	winWidth = $('#intro').width();
}).resize(function(){
	if(TO !== false)
	    clearTimeout(TO);
	 TO = setTimeout(resizeIntro, 200);
})

function popovers(){
	$('body').append('<div id="popover" class="span4"><span class="arrow"></span><h3></h3><p></p></div>');
	var popover = $('#popover');
	var px,
	 	wx,
		offset;
	
	$('[rel]').hover(function(elem){
		popover.stop().fadeTo(250, 1, function(){ popover.show() }).find('h3').text($(this).data('original-title')).next('p:first').text($(this).data('content'));
		
	}, function(){
		popover.stop().fadeTo(500, 0, function(){ popover.hide() });
	}).mousemove(function(event){

		px = event.pageX + popover.width() + 80;
		wx = $(window).width();
		if(px > wx){
			popover.addClass('pright');
			offset = -(popover.width()+100);
		}else{
			popover.removeClass('pright');
			offset = 40;
		}

		popover.css({
			left: event.pageX + offset,
			top: event.pageY - 25
		})

		
	})
	
	popover.hover(function(){
		popover.stop().fadeTo(250, 1, function(){ popover.show() });
	}, function(){
		popover.stop().fadeTo(500, 0, function(){ popover.hide() });
	})
	
}


function toggleSubmitButton(v){
	var button = $('#form_popup button[type=submit]');
	if(v == 'hide'){
		button.css('visibility','hidden');
	}else{
		button.css('visibility','visible');
	}
}

function hidePopup(){
	$('#form_popup').hide();
	$('body').die('click', hidePopup);
}
function closeButton(){
	$('#form_popup .close').on('click',function(){
		$('#form_popup').hide();
		$('body').die('click', hidePopup);
		return false;
	})
}


function form(){
    $('input[data-default]').map(function(){
        var defaultVal = $(this).data('default');
        $(this).focus(function(){
            if($(this).val() == defaultVal){
                $(this).val('')
            }
        }).blur(function(){
            if($(this).val() == ''){
                $(this).val(defaultVal)
            }
        })
    })
}


function popupCookie(){
	
	function hideMainPopup(){
		$('#new-dealer-info').hide();
		$('#new-dealer').show();
	}
	
	$('#new-dealer-info .close').click(function(){
		$('#new-dealer').show();
		$('body').die('click', hideMainPopup);
	})
	
	// $.cookie("popup", null);
	if(! cookie){
		var date = new Date();
		date.setTime(date.getTime() + (60 * 60 * 1000 * 24));
		$.cookie("popup", 'true', { path: '/', expires: date });
		$('#new-dealer-info').show();
		$('#new-dealer').hide();
		$('body').on('click', hideMainPopup);
	}else{
		$('#new-dealer-info').hide();
		$('#new-dealer').show();
	}
}

function fixedMenu(){
	$('body').append('<div id="fixer" />');
	
	$(window).bind('scroll',function(){
		// console.log($('#fixer').offset().top + ' | ' + $('#menu').offset().top)
		if($(window).scrollTop() > 64){
			$('#menu').addClass('fixed');
		}else{
			$('#menu').removeClass('fixed');
		}
	})
}

function sortingElements(){
	$('a[data-sort]').click(function(){
		$this = $(this);
		$this.parents('.sorter').find('a').removeClass('active').end().end().addClass('active')
		
		order = $this.data('order');
		
		$('.sort').each(function(){
			$(this).find('.item').tsort('',{
				'data':$this.data('sort'),
				'order':order
			});
		})
		return false;
	})
}

function gallery(){
	$('.thumbnails a.thumbnail').click(function(){
		$('#main-thumbnail img').attr('src',$(this).attr('href'));
		return false;
	})
	
}








function intro(){
		
	var width = 64;
	var newWidth = 320;
	
	var widthDiff = newWidth - width;
	
	var space = 20;
	
	var first = $('#intro img:first');
	var last = $('#intro img:last');
	
	var hovered = false;
	var smallTitle = $('#title-small');
	var timeout;
	
	$('#intro img').clone().removeClass('current').removeAttr('id').appendTo('#intro');
	$('#intro img').clone().removeClass('current').removeAttr('id').prependTo('#intro');
	
	$('#intro img').map(function(i, e){
		// console.log($(e).height())
		
		// setup
		$(e).css({
			left:width*i + space*i
		})
		
		// title na najeti
		$(e).hover(function(){
			if(! $(this).hasClass('current')){
				hovered = true;
				smallTitle.stop().show().css('opacity',1).text($(this).data('title')).attr('href',$(this).data('href'));
				smallTitle.css('left', $(this).offset().left + ($(this).width()/2 - smallTitle.width()/2) )
			}
		}, function(){
			hovered = false;
			timeout = setTimeout(function(){
				if(hovered == false) smallTitle.stop().fadeOut(200);
				clearTimeout(timeout);
			}, 1000)
		})
		
		smallTitle.hover(function(){
			hovered = true;
		}, function(){
			hovered = false;
			timeout = setTimeout(function(){
				if(hovered == false) smallTitle.stop().fadeOut(200);
				clearTimeout(timeout);
			}, 1000)
		})
		
		// Animace
		$(e).click(function(){
			
			smallTitle.hide();
			
			if($(e).hasClass('current')){
				document.location = $(e).data('href');
				return false;
			}
			
			$('#bubbles ul').hide().find('li').hide();//.dequeue();//.css({opacity:0});
			$('#model-title').text($(this).data('title'));
			$('#model-price').text($(this).data('price')).formatCurrency({
				region: 'cs-CZ',
				roundToDecimalPlace: -2
			});
			$('#model-subtitle').text($(this).data('subtitle'));			
			
			
			$('#intro .current').animate({
				'width':width,
				'bottom':30
			}, 500, function(){
				var center = $(window).width()/2 - newWidth/2;//$this.width()/2
				var newLeft = center - $(e).offset().left;
				$('#intro .current').removeClass('current');
				$(e).animate({
					'left': center,
					'width':newWidth,
					'bottom':0
				}, function(){
					$(e).addClass('current');
					
					$('#'+$(this).data('bubbles')).show().find('li').each(function(i,e){
						$(this).delay(i*100).queue(function(){
							// $(this).animate({
							// 	'opacity':'1'
							// }, 250).dequeue();
							if($.browser.msie){
								$(this).show().dequeue();;
							}else{
								$(this).fadeIn(250).dequeue();;
							}
						})
					})
				})
				$(e).nextAll().map(function(){
					$(this).animate({
						'left': $(this).offset().left + newLeft + widthDiff,
						'bottom':30
					})
				})
				$(e).prevAll().map(function(){
					$(this).animate({
						'left': $(this).offset().left + newLeft,
						'bottom':30
					})
				})
			})
			$('#intro img.current').nextAll().map(function(i, n){
				$(this).animate({
					'left': $(this).offset().left - widthDiff,
					'bottom':30
				})
			})
		})
	})
		
	
	// first.addClass('current')
	var current = $('#intro img.current:first');
	
	var center = $('#intro').width()/2 - newWidth/2;//$this.width()/2
	var newLeft = center - current.offset().left;
	
	current.animate({
		'left': center,
		'width':newWidth,
		'bottom':0
	}, function(){
		$('#'+$(this).data('bubbles')).show().find('li').each(function(i,e){
			$('#model-title').text(current.data('title'));
			$('#model-price .price-format').text(current.data('price')).formatCurrency({
				region: 'cs-CZ',
				roundToDecimalPlace: -2
			});
			$('#model-subtitle').text(current.data('subtitle'));
			$(this).delay(i*100).queue(function(){
				// $(this).animate({
				// 	'opacity':'1'
				// }, 250).dequeue();
				if($.browser.msie){
					$(this).show().dequeue();;
				}else{
					$(this).fadeIn(250).dequeue();;
				}
			})
		})
	})
	current.nextAll().map(function(){
		$(this).animate({
			'left': $(this).offset().left + newLeft + widthDiff
		})
	})
	current.prevAll().map(function(){
		$(this).animate({
			'left': $(this).offset().left + newLeft
		})
	})
	
	current.next('ul.bubbles').show();
}



function sinfinCredit(){
	var span = $('#credit span.credit');
	var width = span.outerWidth('true');
	// var min = ($.browser.msie && $.browser.version <= 7) ? 0 : 0;
	var min = 0;
	$('#credit').css('width',min);
	span.css('color','#fff');
	
	$('#credit').hover(function(){
		span.css('color','#000');
		$('#credit').stop().animate({'width':width-1 + 'px'});
	}, function(){
		$('#credit').stop().animate({'width':min}, function(){
			span.css('color','#fff');
		});
	})
}










