String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
};
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
};


$.extend(true, {
    pet24 : {
        ajax_search_suggestions : function (input, results_div)
        {
            // Configuration
            var delay_ms            = 500;
            var min_chars           = 1;
            var results_limit       = 15; // Limituojam rezultatus, kad popupas neisliptu uz lango ribu
            
            var last_search_str     = '';
            var search_timeout      = undefined;
            
            /****** PUBLIC ******/
            
            this.handle = function()
            {
                $(document).click(function()
                {
                    $(results_div).hide();
                });
                
                
                if ($(input).val().trim() == last_search_str)
                {
                    if ($(results_div).html().trim() != '')
                        $(results_div).show();
                }
                else
                {
                    if(search_timeout != undefined)
                    {
                        clearTimeout(search_timeout);
                    }
                    
                    search_timeout = setTimeout(function()
                    {
                        search_timeout = undefined;

                        if ($(input).val() != last_search_str)
                        {
                            last_search_str = $(input).val().trim();
                            $(results_div).html('');
                            $(results_div).hide();
                            
                            if ($(input).val().trim() != '' && $(input).val().length >= min_chars)
                            {
                                var data  = {
                                    fn: 'search',
                                    key: last_search_str
                                };
                                
                                $.get($.pet24.ajax_url, data, function(json)
                                {
                                    $(results_div).html('');
                                    
                                    if (json.success)
                                    {
                                        for (var i = 0; i < json.results.length; i++)
                                        {
                                            if (results_limit > 0 && i >= results_limit)
                                                break;
                                            
                                            $(results_div).append('<a href="'+json.results[i].uri+'">'+json.results[i].title+'</a>');
                                            $(results_div).show();
                                        }
                                    }
                                }, 'json');
                                
                            }
                        }
                    }, delay_ms);
                }
            }
            
            $(input).keyup(this.handle);
        }
    }
});

$(document).ready(function()
{
    // Ajax search suggestions
    $.pet24.ajax_search_suggestions(
        $("#below_header .search_box input[name='key']"),
        $("#below_header .search_box .ajax_search_suggestions"));
    
    
    //Check product pack
	$('.product .product_info .packs tr').click(function(e) {
		$(".product .product_info .packs tr").removeClass('active');
		$(this).addClass('active');		
		$(".checkbox",this).attr("checked", "checked");
		var quantity=$("select[name=quantity]",this).val()-0;
		var price=$(".price",this).attr('price_value')-0;		
        if (quantity>0 && price>0)	{
            var output=Math.round(quantity*price*100);
            
            if (output % 100 == 0) {
                output = output / 100;
                output = output-0;
                $(".price .price_span",this).html(output);
            } else {
                output = output / 100;
                output = output.toFixed(2);
                $(".price .price_span",this).html(output.replace('.',','));
            }
        }
        
        // Sinchronizacija pasirinktos pakuotes ir nuotraukos 2 dalis
        var pack_id = $("input[name='pack']", this).val();
        var photo_big = false;
        for (var i = 0; i < $.zoom.product_photos.length; i++) {
            if ($.zoom.product_photos[i].pack_id == pack_id) {
                photo_big = $.zoom.product_photos[i].photo_big;
                break;
            }
        }
        if (photo_big != false) {
            // photo_big = photo_big.split("/");
            // photo_big = photo_big.pop();
            // alert($(".product .product_images .product_thumbs a[href='"+photo_big+"']").length);
            // $(".product .product_images .product_thumbs a:has(img[src='"+photo_small+"'])").click();
            $(".product .product_images .product_thumbs a[href='"+photo_big+"']").click();
        }
        
        $(".product .product_info .packs tr .petmoney img").attr('src', 'images/petmoney_gray.gif');
        $(".product .product_info .packs tr.active .petmoney img").attr('src', 'images/petmoney_green.gif');
    });

    //Check login way
    $('.user_choose tr').click(function(e) {
        $(".user_choose tr").removeClass('active');
        $(this).addClass('active');
        $(".checkbox",this).attr("checked", "checked");
        var value=$(".checkbox",this).val();
        if (value==3)
        {
            $(".loginname").addClass("na");
            $(".password").addClass("na");
            $(".password_repeat").addClass("na");
            $(".newsletter").addClass("na");
            $(".usertext2").addClass("na"); 
            $(".usertext1").addClass("na");
            $(".forgot_password").addClass("na");
        }
        else if (value==2)
        {
            $(".loginname").removeClass("na");
            $(".password").removeClass("na");
            $(".password_repeat").removeClass("na");
            $(".newsletter").removeClass("na");
            $(".usertext2").removeClass("na"); 
            $(".usertext1").addClass("na");
            $(".forgot_password").removeClass("na");
        } else {
            $(".loginname").addClass("na");
            $(".password").removeClass("na");
            $(".password_repeat").addClass("na");
            $(".newsletter").addClass("na");
            $(".usertext2").addClass("na"); 
            $(".usertext1").removeClass("na"); 
            $(".forgot_password").removeClass("na");
        }
    });
    
    //Show photo
    $('.product .product_images .product_thumbs a').click(function(e) {
        var img = $("img", this);
        
        // Sinchronizacija pasirinktos pakuotes ir nuotraukos 1 dalis
        var pack_id = false;
        for (var i = 0; i < $.zoom.product_photos.length; i++) {
            if ($.zoom.product_photos[i].photo_small == $(img).attr('src')) {
                pack_id = $.zoom.product_photos[i].pack_id;
                break;
            }
        }
        if (pack_id > 0) {
            // Isvengiam amzino ciklo, nes pakuotes tr click evento handleris vel iskvies sita funkcija
            if ($(".product .product_info .packs tr:has(input[name='pack'][value='"+pack_id+"'])").hasClass("active") == false)
                // $("input[name='pack'][value='"+pack_id+"']").attr("checked", "checked");
                $(".product .product_info .packs tr:has(input[name='pack'][value='"+pack_id+"'])").click();
        }
        var image_url=$(this).attr('href');
        $(".product .product_images .product_container div").css({
            background: 'url('+image_url+') no-repeat center center'
        });
        $(".product .product_images .product_thumbs a").removeClass('active');
        $(this).addClass('active');				
        e.preventDefault();
    });
    
	//Tooltip
	$('.question').hover(
		function() {
			this.tip = this.title;
			$(this).append('<span class="toolTipInfo"><img src="images/tooltip_arrow.gif" class="toolTipArrow"/>'+this.tip+'</span>');
			this.title = "";			
			$('.toolTipInfo',this).show();			
	},
		function() {
			$('.toolTipInfo',this).hide();			
			this.title = this.tip;
		}
	);
    
    // Home banners
    if ($("#home_banners_cnt").length > 0) {
        
        var time;
        var current_item = 0;
        var item_show_for_ms = 5000;
        
        function next_image()
        {
            var next_item = current_item + 1;
            if (next_item >= $("#home_banners_cnt > .banner").length)
                next_item = 0;
            set_image(next_item);
            
            time = setTimeout(next_image, item_show_for_ms);
        }
        function set_image(index)
        {
            if (current_item != index) {
                current_item = index;
                
                $("#home_banners_cnt > .banner").fadeOut();
                $("#home_banners_cnt .selectors > .item img").attr('src', 'images/banner_sel.png');
                
                $("#home_banners_cnt > .banner:eq("+index+")").fadeIn();
                $("#home_banners_cnt .selectors > .item:eq("+index+") img").attr('src', 'images/banner_sel_active.png');
            }
        }
        for (var i = 0; i < $("#home_banners_cnt .selectors > .item").length; i++)
            (function()
            {
                var index = i;
                $("#home_banners_cnt .selectors > .item:eq("+index+")").click(function()
                {
                    clearTimeout(time);
                    set_image(index);
                });
            })();
            
        
        time = setTimeout(next_image, item_show_for_ms);
    }
    
    // Cart step 4 - petlitai
    function updateYourPetmoney(your_petmoney)
    {
        $("#your_petmoney").html(your_petmoney);
        $(".your_petmoney").html(your_petmoney);
    }
    
    function getTotalPrice()
    {
        var totalPrice = $(".total_price_number").html().replace(',', '.')-0;
        return totalPrice;
    }
    function setTotalPrice(totalPrice)
    {
        $(".total_price_number").html(totalPrice.toFixed(2).replace('.', ','));
    }

    $("a[id^=use_petmoney_]").click(function()
    {
        var pack_id = $(this).attr('id').replace('use_petmoney_', '');
        
        var total_price = getTotalPrice();
        
        var petmoney_max = parseInt($("#petmoney_max_"+pack_id).html(), 10);
        if (isNaN(petmoney_max))
            petmoney_max = 0;
        
        var your_petmoney = parseInt($("#your_petmoney").html(), 10);
        if (isNaN(your_petmoney))
            your_petmoney = 0;
        
        var use_petmoney = petmoney_max > your_petmoney ? your_petmoney : petmoney_max;
        
        if (use_petmoney > 0) {
            $("input[name='petmoney_"+pack_id+"']").val(use_petmoney);
            $(".used_petmoney_"+pack_id).html(use_petmoney);
            
            $(".petmoney_not_used_"+pack_id).hide();
            $(".petmoney_used_"+pack_id).show();
            
            your_petmoney   = your_petmoney - use_petmoney;
            updateYourPetmoney(your_petmoney);
            
            total_price     = total_price - use_petmoney;
            setTotalPrice(total_price);
        }
        
        return false;
    });
    
    $("a[id^=cancel_petmoney_]").click(function()
    {
        var pack_id         = $(this).attr('id').replace('cancel_petmoney_', '');
        
        var total_price = getTotalPrice();
        
        var use_petmoney    = parseInt($("input[name='petmoney_"+pack_id+"']").val(), 10);
        if (isNaN(use_petmoney))
            use_petmoney = 0;
        
        var your_petmoney   = parseInt($("#your_petmoney").html(), 10);
        if (isNaN(your_petmoney))
            your_petmoney = 0;
        
        if (use_petmoney > 0) {
            $("input[name='petmoney_"+pack_id+"']").val(0);
            $(".used_petmoney_"+pack_id).html(0);
            
            your_petmoney = your_petmoney + use_petmoney;
            updateYourPetmoney(your_petmoney);
            
            total_price     = total_price + use_petmoney;
            setTotalPrice(total_price);
        }
        
        $(".petmoney_not_used_"+pack_id).show();
        $(".petmoney_used_"+pack_id).hide();
        
        return false;
    });
    // End Cart step 4 - petlitai
    
    // Bottom banner
    $("#bottom_banner").each(function()
    {
        var bottom_banner = $(this);
        
        // (these lines are for IE6-only, on other browsers pure-css works)
        // The problem in IE6 is that it doesn't support position:fixed;
        if ($.browser.msie && $.browser.version < 7.0)
        {
            function fixed()
            {
                $(bottom_banner).width($(window).width());
                
                // // Force redraw to get rid of bottom scrollbar
                // $(bottom_banner).removeClass('IEsucks');
                
                $(bottom_banner).css({
                    position: 'absolute',
                    left: $(window).scrollLeft(),
                    top: $(window).scrollTop() + ($(window).height() - $(bottom_banner).height())
                });
            }
            $(window).scroll(fixed);
            $(window).resize(fixed);
            fixed();
        }
        
        // Always make sure that there is one image out bounds of the screen (in the right),
        // that can slide in
        function drawImages()
        {
            // First remove all drawn images, leaving only the first one
            var images = $("img", bottom_banner);
            // var foundFirstVisible = false;
            for (var i = 0; i < images.length; i++)
            {
                if (i > 0)
                    $(images[i]).remove();
                
                // if (foundFirstVisible)
                    // $(images[i]).remove();
                // else
                // {
                    // if ($(images[i]).is(":visible") == false)
                        // $(images[i]).remove();
                    // else
                        // foundFirstVisible = true;
                // }
            }
            
            // Now - draw the necessary amount of images
            var imagesNecessary = Math.ceil($(window).width() / $("img", bottom_banner).width()) + 1;
            while ($("img", bottom_banner).length < imagesNecessary)
            {
                var last    = $("img:last", bottom_banner);
                var clone   = last.clone();
                clone.css('left', last.position().left + last.width());
                last.after(clone);
            }
        }
        $(window).resize(drawImages);
        drawImages();
        
        // Make the images slide left forever
        function startScroll()
        {
            $("#bottom_banner_inner", bottom_banner).css('left', 0);
            $("#bottom_banner_inner", bottom_banner).animate({
                left:  '-=' + $("img", bottom_banner).width()
            }, $("img", bottom_banner).width() * 30, "linear", startScroll);
        }
        startScroll();
        
        // On mouse over - pause scrolling
        $("#bottom_banner_inner").hover(function()
        {
            $("#bottom_banner_inner", bottom_banner).stop();
        },
        function()
        {
            var leftToScroll = $("#bottom_banner_inner", bottom_banner).position().left + $("img", bottom_banner).width();
            $("#bottom_banner_inner", bottom_banner).animate({
                left:  '-=' + leftToScroll
            }, leftToScroll * 30, "linear", startScroll);
        });
    });
});


//Send link to friend functions
function openSendFriendForm() {
	$(".send_friend").show();
	return ret_false();
}

function closeSendFriendForm() {
	$(".send_friend").hide();
	$(".send_friend form").show();				
	$(".send_friend .error").hide();
	$(".send_friend .success").hide();
	
	$(".send_friend form input[name=email]").val('');
	$(".send_friend form input[name=name]").val('');
	return ret_false();
}

function submitSendFriendForm() {	
	var params = $(".send_friend form input").serialize();	
	$.ajax({
		type: "POST",
		url:  document.location+",ajax.1,action.sendFriend",		
		data: params,
		success: function(sent){			
			if (sent=='1') { 
				$(".send_friend form").hide();
				$(".send_friend .error").hide();
				$(".send_friend .success").show();					
			}
			if (sent=='0') {					
				$(".send_friend .error").show();
			}
		}
	});		
	return ret_false();
}



//Check city
function checkCity(object) {		
	var city_selected=$(object).val();	
	if (city=='Neringa' || city_selected=='Neringa') {
		$("form input[name=reload_same_page]").val('1');
		document.contact_form.submit();
	}
}



//Order product form 
function openOrderProductForm(object) {
	$(".send_product_request").show();
	var pack_id=$(object).attr('pack_id');	
	$(".pack_id").attr({value : pack_id});	
	return ret_false();
}

function closeOrderProductForm() {
	$(".send_product_request").hide();
	$(".send_product_request form").show();				
	$(".send_product_request .error").hide();
	$(".send_product_request .success").hide();
	
	$(".send_product_request form input[name=email]").val('');
	$(".send_product_request form input[name=name]").val('');
	return ret_false();
}

function submitOrderProductForm() {	
	var params = $(".send_product_request form input").serialize();	
	$.ajax({
		type: "POST",		
		url:  document.location+",ajax.1,action.productRequest",
		data: params,
		success: function(sent){			
			if (sent=='1') { 
				$(".send_product_request form").hide();
				$(".send_product_request .error").hide();
				$(".send_product_request .success").show();					
			}
			if (sent=='0') {					
				$(".send_product_request .error").show();
			}
		}
	});		
	return ret_false();
}


//PasswordReminder
function openPasswordReminderForm(object) {
	$(".PasswordReminder").show();	
	return ret_false();
}

function closePasswordReminderForm() {
	$(".PasswordReminder").hide();
	$(".PasswordReminder form").show();				
	$(".PasswordReminder .error").hide();
	$(".PasswordReminder .success").hide();
	
	$(".PasswordReminder form input[name=email]").val('');	
	return ret_false();
}

function submitPasswordReminderForm() {	
	var params = $(".PasswordReminder form input").serialize();	
	$.ajax({
		type: "POST",		
		url:  document.location+",ajax.1,action.remindPassword",
		data: params,
		success: function(sent){			
			if (sent=='1') { 
				$(".PasswordReminder form").hide();
				$(".PasswordReminder .error").hide();
				$(".PasswordReminder .success").show();					
			}
			if (sent=='0') {					
				$(".PasswordReminder .error").show();
			}
		}
	});		
	return ret_false();
}





//Search url building
function search(object){			
	var url=$("input[name=url]",object).attr('value');
	var key=$("input[name=key]",object).attr('value');	
	if (key=='Įveskite kokios prekės ieškote') return ret_false();
	document.location.href = url + key + '/';
	return ret_false();
}



//Add product to cart
function addToCart(){	
	var pack_id=$('.product .product_info .packs .active .checkbox').attr('value');
	var quantity=$('.product .product_info .packs .active .quantity select').val();	
	if (pack_id && quantity) {
		$("#cart").html('<div class="c"><img src="images/indicator.gif"></div>');
		$.ajax({
			type: "POST",
			async: false,
			url:  document.location+",ajax.1,action.addToCart",
			data: {
				pack_id: pack_id,
				quantity: quantity
			}
		});	
		$('html').animate({scrollTop:0}, 'slow');
		$("#cart").load(document.location+",ajax.1,action.cart").slideDown("slow");
	} 
	if (!pack_id) alert('Pasirinkite pakuotę ir spauskite "Į krepšelį"');
	if (pack_id && !quantity) alert('Prekės įsidėti į krepšelį negalima, nes nėra likučio. Prašome spausti "Užsakykite" prie prekės');
	return ret_false();
}

//Remove product from cart
function removeFromCart(pack_id){	
	if (pack_id) {
		$('html').animate({scrollTop:0}, 'slow');
		$("#cart").html('<div class="c"><img src="images/indicator.gif"></div>').load(document.location+",ajax.1,action.cart,delete."+pack_id).slideDown("slow");
	}	
	return ret_false();
}


//Show hide company details block, in step3
function showCompanyBlock(object) {		
	if ($(object).is(':checked')) {	
		$(".company_block").removeClass("na"); 
	} else {
		$(".company_block").addClass("na");		
	}
}


//Return false response
function ret_false() {
	try
	 {
	  // VISTA IE 7
	  window.event.returnValue = false;
	 } catch (error)
	 {
	  // ALL OTHER (MOZILLA, OPERA, SAFARI, IE 6 & 7 ON XP)
	  return false;
	 }	
}

