$(document).ready(function()
{
	if($("#error_triger").attr("value") == 1)
	{
		window.scrollBy(0,420);
	}
	/**
	 *  Send to friend
	 */
	
	$("#send_friend_submit").click( function() {
		$("#formSendToFriend").validate( {
			messages : {
				email : {
					required :'Privalote įvesti el.pašto adresą!',
					email :'Blogai įvestas el.pašto adresas!'
				},
				firstname : {
					required :'Privalote įvesti savo vardą!'
				}
			},
			rules : {
				firstname : {
					required :true
				},
				email : {
					required :true,
					email :true
				}
			}

		});

		if ($("#formSendToFriend").valid()) {
			$('#formSendToFriend').submit();
			$.unblockUI();
		}
	});

	$("#send_friend_close").click( function() {
		// validator.resetForm();
			$.unblockUI();
		});

	$('#send_to_friend').click( function() {
		$.blockUI( {
			message :$('#sendFriendFrom'),
			css : {
			  width :'500px',
			  top:'180px'
			}
		});

	});   
	
	

	//Ask manager form
	
	$("#ask_manager_submit").click( function() {
	$("#form_ask_manager").validate( {
		messages : {
			email : {
				required :'Įveskite el.pašto adresą',
				email :'Neteisingas el.paštas'
			},
			firstname : {
				required :'Įveskite vardą'
			},
			question : {
				required :'Įveskite klausimą'
			}			
		},
		rules : {
			firstname : {
				required :true
			},
			email : {
				required :true,
				email :true
			},
			question : {
				required :true
			}
		}

		});
		
		if ($("#form_ask_manager").valid()) {
			$('#form_ask_manager').submit();
			$.unblockUI();
		}
	});
	
	
	$("#ask_manager_close").click( function() {		
			$.unblockUI();
		});

	$('.ask_manager').click( function() {
		$.blockUI( {
			message :$('#ask_managerForm'),
			css : {
			  width :'500px',
			  top:'180px'
			}
		});
		var product=$(this).attr("product");
		$("#form_ask_manager_product_id").attr({value : product});		
	});   
	
	
	
	/**
	 * ---------------
	 */

	/**
	 * Google MAPs code
	 */
	 var map = null;
   var geocoder = null;

   /**
   * Initialize map
   **/
   function initialize()
   {
     if (GBrowserIsCompatible())
     {
       map = new GMap2(document.getElementById("map"));
       map.addControl(new GLargeMapControl());
			 map.addControl(new GMapTypeControl());
       geocoder = new GClientGeocoder();
       showAddress($("#place_geo option:first").attr("value"));
     }
   }

   if(document.getElementById("map") != null)
   {
   	initialize();
   }

   /**
   * Show selected address
   **/
   function showAddress(address)
   {
     if (geocoder)
     {
       geocoder.getLatLng(
         address,
         function(point)
         {
           if (!point)
           {
             //alert(address + " not found");
           }
           else
           {
             map.setCenter(point, 13);
             var marker = new GMarker(point);
             map.addOverlay(marker);
             marker.openInfoWindowHtml(address);
           }
         }
       );
     }
   }


	$("#place_geo").change(
		function()
		{
			showAddress($(":selected", this).attr("value"));
		}
	);
	/**
	* ---------------------------------------------
	**/


	function reloadMap(long_cor, lat_cor)
	{
		if (GBrowserIsCompatible())
	  {
	  	if(document.getElementById("map") != 'undefined')
	  	{
		    var map = new GMap(document.getElementById("map"));
		    map.centerAndZoom(
		    new GPoint(long_cor, lat_cor), 3);
		    var point = new GPoint(long_cor, lat_cor);
		    var marker = new GMarker(point);
		    map.addOverlay(marker);			
	  	}
	  }
	}


	//Main menu	
	 $('.menu li').hoverIntent(
		function()
		{
			$(".submenu",this).show();
			$("a",this).addClass('active');
		},
		function()
		{
			$(".submenu",this).hide();
			$("a",this).removeClass('active');
		}
	);


	//Categories in homepage
	$('.categories .category .expand').click(
		function(event)
		{
			var parent1=$(this).parent();
			var parent2=parent1.parent();

			//Atidarom
			if ($(".expanded",$(this).parent()).length == 0){
				//Visiems neuzdarytiems
				$(".categories .category .current_category").addClass('hidden');
				$(".categories .category .current_category").removeClass('current_category');
				$(".categories .category .expanded").removeClass('expanded');

				//Konkreciam
				$(this).addClass('expanded');
				$(".all_subcategories",parent2).removeClass('hidden');
				$(".all_subcategories",parent2).addClass('current_category');
			} else
			//Uzdarom
			{
				$(this).removeClass('expanded');
				$(".all_subcategories",parent2).addClass('hidden');
			}

			event.preventDefault();
		}
	);


	//Home page Slider
	$("#slides_controller").jFlow({
		slides: "#slides_content",
		controller: ".jFlowControl", // must be class, use . sign
		slideWrapper : "#jFlowSlide", // must be id, use # sign
		selectedWrapper: "jFlowSelected",  // just pure text, no sign
		duration: 200,
		width: "820px",
		height: "347px"		
	});

	//Product photos controler
	$("#photos_controller").jFlow({
		slides: "#photos_content",
		controller: ".jFlowControl2", // must be class, use . sign
		slideWrapper : "#jFlowSlide2", // must be id, use # sign
		selectedWrapper: "jFlowSelected2",  // just pure text, no sign
		duration: 1,
		width: "428px",
		height: "320px",
		prev: ".jFlowPrev", // must be class, use . sign
		next: ".jFlowNext" // must be class, use . sign
	});


	$(".expander").toggle(function() {
		$("."+$(this).attr("ref")).hide();
		$(this).html('<img src="images/+.gif"/>');
		event.preventDefault();
	}, function() {
		$("."+$(this).attr("ref")).show();
		$(this).html('<img src="images/-.gif"/>');
		event.preventDefault();
	});


  showRegistrationBlock();
	
	$("input[@name='type']").click(function() {
	  var thisValue = $(this).val();
	  switch (thisValue) {
	    case "1":
			$(".type1").show();
			$(".type2").hide();
	      break;
	    case "2":
			$(".type2").show();
			$(".type1").hide();
	      break;
	  }
	});

	function showRegistrationBlock()
	{
	  var int_value = $("input[@name='type']:checked").val();
	  switch (int_value) {
	    case "1":
			$(".type1").show();
			$(".type2").hide();
	      break;
	    case "2":
			$(".type2").show();
			$(".type1").hide();
	      break;
	  }
	}
	
	//Add to cart AJAX action
    $('.add_to_cart').click(function(event){
        event.preventDefault();
        $.ajax({
            cache: false,
            dataType: 'json',
            data: 'product_id=' + $(this).attr("product"),
            type: 'GET',
            url: 'src/pages/add_to_cart.php',
            beforeSend: function(){
                $(this).attr('disabled', 'disabled');
            },
            error: function(){
                $(this).removeAttr('disabled');
                alert('Klaida!');
            },
            success: function(response){
                $(this).removeAttr('disabled');
                $('#cartQuantity').html(response.quantity);
                if (response.completed) {
                    alert('Prekė sėkmingai patalpinta Jūsų krepšelyje.');
                } else {
                    alert('Šio produkto kiekis sandelyje yra mažesnis nei Jūsų norimas pirkti.');
                }
            }
        });
    });
	
	
	//Add to comparison	
	$('.add_to_comparison').click(
		function(event)
		{							
			var product_id = $(this).attr("product");			
			$('html').animate({scrollTop:0}, 'slow');
			$("#comparison").hide();
			$('#comparison').html('<div class="c"><img src="images/preloader.gif"/><div>').load("src/pages/add_to_comparison.php?product_id=" + product_id);
			$("#comparison").show('slow');			
		}
	);
	
	//Update quantity
	$('.change_quantity').change(
		function()
		{
			var url=$(this).val();
			window.location = url;
		}
	);	
	
	//Load address data by chossen delivery city
	$('.shop_city').change(
		function()
		{
			var city_id=$(this).val();
			$('#shop_addresses').html('<img src="images/preloader.gif"/>').load("src/pages/get_shop_addresses.php?city_id=" + city_id);
		}
	);	
	
	//Hide unchossen delivery types
	$('.delivery_type').click(
		function()
		{
			var parent1=$(this).parent();
			var parent2=parent1.parent();
			$(".right").hide();
			$(".right",parent2).show();
		}
	);	
	
	//Svarbu zinoti blokelio expanderis
	$(".important").toggle(function() {
		var parent1=$(this).parent();		
		$(".important_content",parent1).show();
		$(".important_pic",parent1).html('<img src="images/-.gif"/>');		
		event.preventDefault();
	}, function() {
		var parent1=$(this).parent();		
		$(".important_content",parent1).hide();
		$(".important_pic",parent1).html('<img src="images/+.gif"/>');	
		event.preventDefault();
	});
	
	

});



/* function gotoUrl() {
	var redirect;
	redirect = document.getElementById('newUrl').value;
	document.location.href = redirect;
} */

function gotoUrl2(base,val){		
	if (!val) { 
		return false; 
	}
	else {
		document.location.href = base + val + '/';	
		return false;
	}
}
	