$(function(){

	//ie only
	/*
	if($.browser.msie && $.browser.version < 10){
		$('.green_button, .yellow_button, .red_button')
			.append('<span class="lt"></span><span class="rt"></span><span class="lb"></span><span class="rb"></span>')
			.css('position' ,'relative');
	}
	*/

	if($.browser.msie && $.browser.version < 9){

		$('#sitenav, #tab_nav ul li, .green_button')
			.append('<span class="lt"></span><span class="rt"></span><span class="lb"></span><span class="rb"></span>')
			.css('position' ,'relative');
		$('.add_to_cart button')
			.append('<span class="lt"></span><span class="rt"></span>')
			.css('position' ,'relative');
	}


	$('#sitenav li:last-child').addClass('last');
	$('#sitenav li:first-child').addClass('first');

	//textbox values

	swap_val = [];
	$(".swap").each(function(i){
		swap_val[i] = $(this).val();
		$(this).focusin(function(){
			if ($(this).val() == swap_val[i]) {
				$(this).val("");
			}
		}).focusout(function(){
			if ($.trim($(this).val()) == "") {
				$(this).val(swap_val[i]);
			}
		});
	});


	//change tabs
	$('#tab_nav li').click(function(){
		var speed = 500;
		var elem = $(this);
		var content = $('#tab_content');
		var not_new = elem.hasClass('active');
		var id = elem.attr('data-tab');

		$('#tab_nav li.active').removeClass('active');
		content.find('div.active').slideUp(speed).removeClass('active');
		if(not_new == false){
			elem.addClass('active');
			content.find('div.tab_'+id).slideDown(speed).addClass('active');
		}
		var url = elem.attr('data-url');

		if(url != undefined){
			window.location.replace(url);
		}
	});

	//front prduct hover
	$('.tab_1 #product_list li').hover(function(){
		 $(this).find('p.more_info').stop(true, true).slideDown(300);
	}, function(){
		 $(this).find('p.more_info').stop(true, true).slideUp(300);
	});


	$(".lightbox-ama").colorbox({  });
	$(".avaGal").colorbox({ rel: "follow", current:'{current} / {total}', scalePhotos: true, maxWidth: 800, maxHidth: 600 });

	//basket
	$("#product_list li a.osta_button").click(function() {
		var elem 			= $(this).parent().parent().parent();
		var basket 			= $('#tab_nav #header_cart');
		var image 			= elem.find('a img');
		animate_basket(basket, image, elem);
	});

	$(".add_to_cart button").click(function() {
		var elem 			= $(this).parent().parent().parent();
		var basket 			= $('#tab_nav #header_cart');
		var image 			= elem.find('.image .featured img');
		animate_basket(basket, image, elem);
		return false;
	});


	//product tooltip
	$('.buttons .icons a').hover(function(){
		var elem = $(this).find('.tooltip');
		elem.stop(true, true).fadeIn(500);
	}, function(){
		var elem = $(this).find('.tooltip');
		elem.stop(true, true).fadeOut(500);
	});

	//change list layout
	$('.options_bar .layout li').click(function(){
		var elem = $(this);
		var name = elem.attr('id');
		elem = $('.options_bar .layout li#'+name);

		$('.options_bar .layout li.active').removeClass('active');
		elem.addClass('active');
		$('#content #product_list').removeClass().addClass(name);
		equal_height('#sidebar, #content');
	})


});

$(window).load(function() {

	equal_height('.campaign, .facebook');
	$("#featured").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, false);
});

function equal_height(elem)
{
	var maxHeight=0;
	elem = $(elem);
	elem.css('height', 'auto');
    elem.each(function(){
		var sub_elem = $(this);
        if(sub_elem.height()>maxHeight)
            maxHeight=sub_elem.height();
    });
	elem.css('height', maxHeight);
}

function animate_basket(basket, image, product)
{
	var productX 		= image.offset().left;
	var productY 		= image.offset().top;

	var basketX 		= basket.offset().left;
	var basketY 		= basket.offset().top;
	var gotoX 			= basketX - productX;
	var gotoY 			= basketY - productY;

	var newImageWidth 	= image.width() / 3;
	var newImageHeight	= image.height() / 3;

	image
	.clone()
	.prependTo(product)
	.css({'position' : 'absolute', 'z-index' : 900})
	.animate({opacity: 0.7}, 100 )
	.animate({opacity: 0, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200 );
}

function setPerPage(k) {
	$.ajax({
		type: "POST",
	    url: "moodulid/tootekataloog/user.AjaxCalls.php",
	    data: "tegevus=savePerPage&perPage="+$(k).val(),
	    success: function(html){

	    	location.reload();
	    }
	});
}

function setSort(k) {
	$.ajax({
		type: "POST",
	    url: "moodulid/tootekataloog/user.AjaxCalls.php",
	    data: "tegevus=saveSortType&sortType="+$(k).val(),
	    success: function(html){
	    	location.reload();
	    }
	});
}

function setFilter(k, katId) {
	$.ajax({
		type: "POST",
	    url: "moodulid/tootekataloog/user.AjaxCalls.php",
	    data: "tegevus=setFilter&filterType="+$(k).val()+"&kat="+katId,
	    success: function(html){
	    	location.reload();
	    }
	});
}

function setDirection(k) {
	$.ajax({
		type: "POST",
	    url: "moodulid/tootekataloog/user.AjaxCalls.php",
	    data: "tegevus=saveSortDirection&sortDirection="+k,
	    success: function(html){
	    	location.reload();
	    }
	});
}

function setPageView(view) {
	$.ajax({
		type: "POST",
	    url: "moodulid/tootekataloog/user.AjaxCalls.php",
	    data: "tegevus=savePageView&view="+view,
	    success: function(html){
	    }
	});
}
function addToBasket(inc)
{
	$.ajax({
		type: "POST",
	    url: "moodulid/ostukorv/user.AjaxCalls.php",
	    data: $("#addToBasket").serialize()+"&inc="+inc,
	    dataType: "json",
	    success: function(json){
	    	$("#header_cart").html(json.pais);
	    	if(!inc) $("#kogus_"+$("#prodId").val()).val(json.kogus);
	    }
	});
}

function addToBasketM(id)
{
	$('#prodId').val(id);
	$('#bkogus').val($('#kogus_'+id).val());
	if($('#kogus_'+id).val()==0)
	{
		$('#kogus_'+id).val(1);
	}
	addToBasket(0);
}

function qryHowOld(varAsOfDate, varBirthDate)
     {
     var dtAsOfDate;
     var dtBirth;
     var dtAnniversary;
     var intSpan;
     var intYears;
     var intMonths;
     var intWeeks;
     var intDays;
     var intHours;
     var intMinutes;
     var intSeconds;
     var strHowOld;

     // get born date
     dtBirth = new Date(varBirthDate);

     // get as of date
     dtAsOfDate = new Date(varAsOfDate);

     // if as of date is on or after born date
    if ( dtAsOfDate >= dtBirth )
        {

        // get time span between as of time and birth time
        intSpan = ( dtAsOfDate.getUTCHours() * 3600000 +
                    dtAsOfDate.getUTCMinutes() * 60000 +
                    dtAsOfDate.getUTCSeconds() * 1000    ) -
                 ( dtBirth.getUTCHours() * 3600000 +
                    dtBirth.getUTCMinutes() * 60000 +
                    dtBirth.getUTCSeconds() * 1000       )

        // start at as of date and look backwards for anniversary

        // if as of day (date) is after birth day (date) or
        //    as of day (date) is birth day (date) and
        //    as of time is on or after birth time
        if ( dtAsOfDate.getUTCDate() > dtBirth.getUTCDate() ||
             ( dtAsOfDate.getUTCDate() == dtBirth.getUTCDate() && intSpan >= 0 ) )
           {

           // most recent day (date) anniversary is in as of month
           dtAnniversary =
              new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                  dtAsOfDate.getUTCMonth(),
                                  dtBirth.getUTCDate(),
                                  dtBirth.getUTCHours(),
                                  dtBirth.getUTCMinutes(),
                                  dtBirth.getUTCSeconds() ) );

           }

        // if as of day (date) is before birth day (date) or
        //    as of day (date) is birth day (date) and
        //    as of time is before birth time
        else
           {

          // most recent day (date) anniversary is in month before as of month
           dtAnniversary =
              new Date( Date.UTC( dtAsOfDate.getUTCFullYear(),
                                  dtAsOfDate.getUTCMonth() - 1,
                                  dtBirth.getUTCDate(),
                                  dtBirth.getUTCHours(),
                                  dtBirth.getUTCMinutes(),
                                  dtBirth.getUTCSeconds() ) );

           // get previous month
           intMonths = dtAsOfDate.getUTCMonth() - 1;
           if ( intMonths == -1 )
              intMonths = 11;

           // while month is not what it is supposed to be (it will be higher)
           while ( dtAnniversary.getUTCMonth() != intMonths )

              // move back one day
              dtAnniversary.setUTCDate( dtAnniversary.getUTCDate() - 1 );

           }

        // if anniversary month is on or after birth month
        if ( dtAnniversary.getUTCMonth() >= dtBirth.getUTCMonth() )
           {

           // months elapsed is anniversary month - birth month
           intMonths = dtAnniversary.getUTCMonth() - dtBirth.getUTCMonth();

           // years elapsed is anniversary year - birth year
           intYears = dtAnniversary.getUTCFullYear() - dtBirth.getUTCFullYear();

           }

        // if birth month is after anniversary month
        else
           {

           // months elapsed is months left in birth year + anniversary month
           intMonths = (11 - dtBirth.getUTCMonth()) + dtAnniversary.getUTCMonth() + 1;

           // years elapsed is year before anniversary year - birth year
           intYears = (dtAnniversary.getUTCFullYear() - 1) - dtBirth.getUTCFullYear();

           }

        // to calculate weeks, days, hours, minutes and seconds
        // we can take the difference from anniversary date and as of date

        // get time span between two dates in milliseconds
        intSpan = dtAsOfDate - dtAnniversary;

        // get number of weeks
        intWeeks = Math.floor(intSpan / 604800000);

       // subtract weeks from time span
        intSpan = intSpan - (intWeeks * 604800000);

        // get number of days
        intDays = Math.floor(intSpan / 86400000);

        // subtract days from time span
        intSpan = intSpan - (intDays * 86400000);

        // get number of hours
        intHours = Math.floor(intSpan / 3600000);

        // subtract hours from time span
        intSpan = intSpan - (intHours * 3600000);

        // get number of minutes
        intMinutes = Math.floor(intSpan / 60000);

        // subtract minutes from time span
        intSpan = intSpan - (intMinutes * 60000);

        // get number of seconds
        intSeconds = Math.floor(intSpan / 1000);

        // create output string
        if ( intYears > 0 )
           if ( intYears > 1 )
              strHowOld = intYears.toString();
           else
              strHowOld = intYears.toString();
        else {
           strHowOld = '0';
        }

        }
     else {
     	strHowOld = '0';
     }

// return string representation
return strHowOld
}
