$(document).ready(function() {
	jQuery('#jcarousel').jcarousel();

	// h1 correction for small screens
	$.fn.dimensions = function() {
		if ($(window).width() < 1160) {
			$('h1.title').css('left', '580px');
		} else {
			$('h1.title').css('left', '50%');
		}
	};
	$.fn.dimensions();
	$(window).resize(function() {
		$.fn.dimensions();
	});

	//console.log(maximalni_cena);
  if (window.maximalni_cena === undefined) maximalni_cena = 1000; //JK prenasi se z filtru
	$('a.fancybox').fancybox();
/*
	$('.jcarousel').jcarousel({
		scroll: 5
	});
*/
	/*$('.jcarousel-set').jcarousel({
		scroll: 1
	});*/

/*
    $('ul.moving_boxes').movingBoxes({
		startPanel   : 1,      // start with this panel
		width        : 680,    // overall width of movingBoxes (not including navigation arrows)
		panelWidth   : 0.85,
    reducedSize  : 0.75,
    wrap         : false,   // if true, the panel will "wrap" (it really rewinds/fast forwards) at the ends
		buildNav     : true,   // if true, navigation links will be added
		fixedHeight  : true,
    easing       : 'swing',
    navFormatter : function(){ return "&#9679;"; } // function which returns the navigation text for each panel
	});
*/




	$('a[title]').tooltip({
		track: true,
		showURL: false
	});
	$('#giftimg1, #giftimg2, #giftimg3, #giftimg4, #giftimg5, #giftimg6').tooltip({ 
    delay: 0, 
    showURL: false, 
    bodyHandler: function() { 
        return $("<img/>").attr("src", this.name); 
    } 
  });
  $('#giftimg').tooltip({ 
    delay: 0, 
    showURL: false, 
    bodyHandler: function() { 
        return $("<img/>").attr("src", this.src); 
    } 
  });
	$('#slider').easySlider({
		prevText: '',
		nextText: '',
		auto: true,
		continuous: true,
		pause: 5000
	});

	$('#div-4 form').bind('submit', function() {
    console.log($('#f1_jmeno'));
		if ($('#f1_jmeno').val().length < 1 || $('#f1_prijmeni').val().length < 1 || $('#f1_email').val().length < 1 || $('#f1_dotaz').val().length < 1) {
			alert('Vyplňte prosím povinné položky.');
			return false;
		}
		$.ajax({
			type: 'POST',
			cache: false,
			url: '/product/ask/',
			data: $(this).serializeArray(),
			success: function(data) {
				$.fancybox('<span style="color: #000;">' + data + '</span>');
			}
		});
		return false;
	});
	$('#div-5 form').bind('submit', function() {
		if ($('#f2_jmeno').val().length < 1 || $('#f2_email').val().length < 1) {
			alert('Vyplňte prosím povinné položky.');
			return false;
		}
		$.ajax({
			type: 'POST',
			cache: false,
			url: '/product/recommend/',
			data: $(this).serializeArray(),
			success: function(data) {
				$.fancybox('<span style="color: #000;">' + data + '</span>');
			}
		});
		return false;
	});

	$('[placeholder]').focus(function() {
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		}
	}).blur(function() {
		var input = $(this);
		if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
      $('#searchError').hide();
      input.removeClass('error');
		}
	}).blur().parents('form').submit(function() {
		$(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				input.val('');
			}
		})
	});

	$('.slick-down').change(function() {
		$('.slick-down').attr('checked', true);
		$('#slickbox-2').slideDown('fast');
		return false;
	});
	$('.slick-up').change(function() {
		$('.slick-up').attr('checked', true);
		$('#slickbox-2').slideUp('fast');
		return false;
	});
	$('.slick-toggle').click(function() {
		$('#slickbox').slideToggle('fast');
		return false;
	});

//	$('.user').hover(function() {
//		$('.login').slideDown('fast');
//		return false;
//	}, function() {
//		$('.login').slideUp('fast');
//		return false;
//	});

// rozbalovaci login menu 
	$('.user').hover(function() {
		$(this).find('.login').show(); // .slideDown('fast').show()
		}, function() {
		$(this).find('.login').hide(); // .slideUp('slow').hide()
	});
	

	$('#menu > li:last-child').css('border-bottom', 'none');
	$('#menu > li').each(function(i) {
		$(this).children('a').css('background-image', 'url(/img/menu-icon-' + i + '.png)');
	});

	//$('#hidden-filters').hide();
	//$('#filters-down').show();
	$('#filters-down').click(function() {
		$('#hidden-filters').slideDown('fast');
		$('#filters-down').hide();
		$('#filters-up').show();
		return false;
	});
	$('#filters-up').click(function() {
		$('#hidden-filters').slideUp('fast');
		$('#filters-up').hide();
		$('#filters-down').show();
		return false;
	});

	$('#slider-range').slider({
		range: true,
		min: 0,
		max: maximalni_cena,
		values: [$('#cena_od').val(), $('#cena_do').val()],
		slide: function(event, ui) {
			$('#discount').val(ui.values[0] + '-' + ui.values[1]);
			$('#discount-1').text(ui.values[0]);
			$('#discount-2').text(ui.values[1]);
		},
    stop: function(event, ui){
      $('#cena_od').val(ui.values[0]);
      if(ui.values[1] == maximalni_cena){
        $('#cena_do').val('');
      }else{
        $('#cena_do').val(ui.values[1]);
      }
      
      $("#form_filters").submit();
    }

	});
	$('#discount-1').text($('#slider-range').slider('values', 0));
	$('#discount-2').text($('#slider-range').slider('values', 1));

	$('.product-small-card .description').hide();
	$('.product-small-card').hover(function() {
		$(this).find('.description').slideDown('fast');
		return false;
	}, function() {
		$(this).find('.description').slideUp('fast');
		return false;
	});

	$('.bookmarks li').each(function() {
		var tab = $(this).attr('id').split('-');
		var div = '#div-' + tab[1];
		if ($(div).length) {
			$(this).addClass('active');
			$(div).show();
			return false;
		};
	});
	$('.bookmarks li a').click(function() {
		$('.bookmarks li').each(function() {
			var tab = $(this).attr('id').split('-');
			var div = '#div-' + tab[1];
			$(this).removeClass('active');
			$(div).hide();
		});
		$(this).parent().addClass('active');
		var tab = $(this).parent().attr('id').split('-');
		var div = '#div-' + tab[1];
		$(div).show();
	});

	$('.more-categories').css('height', '14px');
	$('#more-categories').show();
	$('#more-categories').click(function() {
		$('.more-categories').css('height', 'auto');
		$('#more-categories').hide();
		$('#less-categories').show();
		return false;
	});
	$('#less-categories').click(function() {
		$('.more-categories').css('height', '14px');
		$('#less-categories').hide();
		$('#more-categories').show();
		return false;
	});

	$('.more-shipping').css('height', '30px');
	$('#more-shipping').show();
	$('#more-shipping').click(function() {
		$('.more-shipping').css('height', 'auto');
		$('#more-shipping').hide();
		$('#less-shipping').show();
		return false;
	});
	$('#less-shipping').click(function() {
		$('.more-shipping').css('height', '30px');
		$('#less-shipping').hide();
		$('#more-shipping').show();
		return false;
	});

$("#topBarSearchString").autocomplete("/shop/searchAutocomplete/", {
   minChars: 3,
   max: 7,
   width: 220,
   selectFirst: false,
   scroll: false,
   matchContains: true,
   dataType: 'json',
   parse: function(data) {
     var array = new Array();
     for(var i=0;i<data.length;i++){
        array[array.length] = {data: data[i], value: data[i].nazev, result: data[i].nazev};
     }
     return array;
   },
   formatItem: function(item, pos, count){
     return item.nazev;
   }
});
$("#topBarSearchString").result(function(event, data, formatted){
   window.location.href = data.url;
});

$("#kosikForm").validate({});

$("#search").validate({
  rules: {dotaz: {minlength: 2, required: true}}
});

$("#attachment").validate({
  rules: {required: true}
});

//registrační formulář
$("form[name=form1]").validate({
 rules: {captcha_1 : {required: true, remote: '/shop/validateCaptcha/'}},
 messages: {captcha_1: "Neplatný ověřovací znak."}
});
$("#form_customer").validate({
 submitHandler: function(form) {
   	$('#uf_stat').removeAttr('disabled');$('#d_stat').removeAttr('disabled');
    form.submit();
   }
});

//google talk
$.ajax({
  type: "GET",
	url: "/shop/gtStatus/",
	dataType: 'json',
	success: function(msg){
	  if(msg.status){
//      $('#gt_online img').attr('src', msg.img);
      $('#gt_online a').attr('href', msg.link);
      $('#gt_offline').hide();
      $('#gt_online').show();
    }
  }
});



 
});


function bookmarks(objId) {
	document.getElementById('podrobnyPopis').style.display = 'none';
	document.getElementById('parametryZbozi').style.display = 'none';
	document.getElementById('dalsiObrazky').style.display = 'none';
	document.getElementById('souboryKeStazeni').style.display = 'none';
	if (document.getElementById('diskuzeKProduktu')) {
		document.getElementById('diskuzeKProduktu').style.display = 'none';
	}
	document.getElementById(objId).style.display = 'block';
	return false;
}

function platbyUpdate() {
	if (document.getElementById('platbyBox')) {
		var box = document.getElementById('platbyBox'); // box s vypisem plateb
		var stat1 = document.getElementById('uf_stat'); // stat v adrese
		var stat2 = document.getElementById('d_stat'); // stat v dodaci adrese
		var dodaci = document.getElementById('pouzit_doruc_ne'); // dodaci adresa
		var platby1 = new Array();
		var platby2 = new Array();
		if ((dodaci.checked && (stat1.value != 'Česká republika')) || (!dodaci.checked && (stat2.value != 'Česká republika'))) {
			platby1 = getElementsByClassName(box, 'tr', 'platba_sk');
			platby2 = getElementsByClassName(box, 'tr', 'platba_cz');
		} else {
			platby1 = getElementsByClassName(box, 'tr', 'platba_cz');
			platby2 = getElementsByClassName(box, 'tr', 'platba_sk');
		}
		for (var i=0; i<platby1.length; i++) {
			platby1[i].style.display = 'table-row';
			if (i == 0) {
				platby1[i].getElementsByTagName('input')[0].checked = true;
			}
		}
		for (var i=0; i<platby2.length; i++) {
			platby2[i].style.display = 'none';
		}
	}
}

function checkMinLength(objId, minLength, msg) {
 var obj = getObj(objId)
 if (obj.value.length<minLength) {
		if (msg!='') alert(msg);
		return false;
	} else return true;
}

function addComment(title, parent) {
	document.getElementById('addComment').style.display = 'block';
	var changer = document.getElementById('titulek');
	changer.value = 'Re: ' + title;
	changer = document.getElementById('id_parent');
	changer.value = parent;
}

/**
  * Signs up for the neswletter using ajax request.
  * @param email - email address
  * @return
  */
 function signUpNewsletter(email, invalid_email_message){
  if(!validateEmail(email)){
    alert(invalid_email_message);
    return false;
  }

  var dataToSend = "email=" + email + "&ajax=1";
   $.ajax({
    type: "GET",
    url: "/shop/singUpNewsletter/",
    data: dataToSend,
    dataType: 'text',
    success: function(msg){
     alert(msg);
    }
   }
   );
  return false;
 }

 /**
  * Simple email validation, checks @ position and last dot's position
  */
 function validateEmail(email){
  var atpos=email.indexOf("@");
  var dotpos=email.lastIndexOf(".");
  return (atpos>0 && dotpos>atpos+1 && dotpos+2<email.length);
 }

/**
 * Opinion pool vote.
 */
function opinionPool(id_pool, id_row){
  var dataToSend = "id_anketa=" + id_pool + "&id_row=" + id_row + "&ajax=1";
  $.ajax({
   type: "GET",
   url: "/shop/opinionPool/",
   data: dataToSend,
   dataType: 'text',
   success: function(msg){
    alert(msg);
   }
  }
  );
  return false;
}


/**
 * Loads payments and shipping based on 'country_code' using
 * template 'dopravy_platby_rows.tpl' and appends them to alement with id = 'elem_id'.
 * @param elem_id - where to put result
 * @param country - country code or name
 * @param radio - radio button which must be checked to perform country selection
 */
var pay_index=0;
function loadPayShip(elem_id, country, radio){
 if(radio && !$('#'+radio).attr('checked')){
		return false;
 }
 pay_index++;
 var my_index = pay_index;

 //convert name to code using option id
 var elem = $('#'+elem_id);
 elem.find('tr[id!="platby_loading"]').remove();
 $('#platby_loading').show();
  var dataToSend = "country=" + country;
	$.ajax({
		type: "GET",
		url: "/order/loadPayShip/",
		data: dataToSend,
		dataType: 'html',
		success: function(msg){
		if(my_index == pay_index){
      $('#platby_loading').hide();
			elem.append(msg);
		}
		}
	}
	);
	return false;

}
