$(document).ready(function(){

	$("#search-bar #search_query").focus(function(){
		if($(this).val() == "Search for Products"){
			$(this).val('');
		}
	});

	$("#search-bar #search_query").blur(function(){
		if($(this).val() == ""){
			$(this).val('Search for Products');
		}
	});
	
	$("a.fbox").fancybox({
		
	});
	
	$('#login-panel').hide();

	$('#login-btn a').click(function(event){
		event.stopPropagation();
		
		$('#login-panel').slideToggle();
		
		$('#search-panel').slideUp();
		return false;
	});
	
	$('#search-panel').hide();
	
	$('#search-btn a').click(function(event){
		event.stopPropagation();
		
		$('#search-panel').slideToggle();
		
		$('#login-panel').slideUp();
		
	});
	
	$('#username').bind("keydown", function(e) {
		if (e.keyCode == 13) {
		login();
		return false; //prevent default behaviour
		}
	});
	
	$('#password').bind("keydown", function(e) {
		if (e.keyCode == 13) {
		login();
		return false; //prevent default behaviour
		}
	});
	
	/* Login ajax */
	$('#validate-btn').click(function(event){
	
	
	
	login();
	event.stopPropagation();
	
	return false;
	
	
	
	});
	
	function login(){

     $("#msgBox").removeClass().addClass('messagebox').text('Validating').fadeIn(1000);

     $.post(global_baseurl + "dashboard/auth/go_ajax",{ username:$('#username').val(),password:$('#password').val(),rand:Math.random() } ,function(data)
     {		
     //alert(data);
       if(data=='true') 
       {
             $("#msgBox").fadeTo(200,0.1,function()  //start fading the messagebox
             {
				
               $(this).html('Logging in').addClass('messageboxok').fadeTo(900,1,
               function()
               {
               	
                  document.location=global_baseurl;
               });
             });
       }
       else
       {
             $("#msgBox").fadeTo(200,0.1,function() //start fading the messagebox
             {
				
               $(this).html('Wrong').addClass('messageboxerror').fadeTo(900,1);
             });
       }
    });
    return false;//not to post the  form physically
};

	$(".login").click(function(e){
		$("#message-panel").fadeIn();
		$("#message-panel .close").click(function(){
			$("#message-panel").fadeOut();
		
		})
		e.stopPropagation();
		return false;
	});
	
	

	/* Cart function */
	
	
		


		$(".product-item .add-to-cart").click(function() {
			add_to_cart($(this).parent().find('.id').html());
			//console.log($(this).parent().find('.id').html());
			return false;
		});
		
		
		
		
		
		/*function update_cart(){
			
			
			
			var id = $(this).parent().find('#fcustomer').val();
			
				//var items = new Array();

				var items = $('#cart_form').serialize();
				
			
			
			//console.log(id);

			var link = "/site/"; 

			 $.post(link + "cart/update_cart", { customer_id: id, data: items, ajax: '1' },
	  			function(data){

	  			if(data == 'true'){

	    			$.get(link + "cart/show_cart", function(cart){
	  					$(".cart_list").html(cart);
					});
					



	    		}else{
	    			alert("Product does not exist");
	    		}



	 		 }); 

			return false;
			
		}
		
		*/
		
		

		$(".empty").live("click", function(){
	    	$.get(link + "cart/empty_cart", function(){
	    		$.get(link + "cart/show_cart", function(cart){
	  				$("#cart_content").html(cart);
				});
			});

			return false;
	    });
	    
	$('#loader').hide();
	
	
	
	

	/* List */
	$(".accordion").click(function(event){
	
	
	
		event.stopImmediatePropagation();
	
		$(this).find(".sub-list").slideToggle('fast');
	
	
	
	})

	var $scrollingDiv = $("#cart");
	
	/*
	$(window).scroll(function(){
		if($(window).scrollTop() > 820)		{
		
		$scrollingDiv
			.stop()
			.animate({"marginTop": ($(window).scrollTop() - 820) + "px"}, "slow" );	
		
		} else {
			$scrollingDiv
				.stop()
				.animate({"marginTop": (20) + "px"}, "slow" );
		}		
	});
	*/
	
	function moveCart(){
		if($(window).scrollTop() > 900)		{
		if($(window).height() < $('.cart_list').height()){
		
			//Stick to Bottom
			if((($(window).scrollTop() - 820) + ($(window).height() - $('.cart_list').height() - 30)) > 0){
			$scrollingDiv
			.stop()
			.animate({"marginTop": (($(window).scrollTop() - 900) + ($(window).height() - $('.cart_list').height() - 30)) + "px"}, "slow" );	
			} else {
			$scrollingDiv
				.stop()
				.animate({"marginTop": (20) + "px"}, "slow" );
		}
		}
		 else {
		 	//Stick to top
		 	if((($(window).scrollTop() - 820) + ($(window).height() - $('.cart_list').height() - 30)) > 0){
		$scrollingDiv
			.stop()
			.animate({"marginTop": (($(window).scrollTop() - 900) ) + "px"}, "slow" );	
		} else {
			$scrollingDiv
				.stop()
				.animate({"marginTop": (20) + "px"}, "slow" );
		}
		
		
		}
		
		} else {
			$scrollingDiv
				.stop()
				.animate({"marginTop": (20) + "px"}, "slow" );
		}		
	};
	
	$(window).scroll(function(){
		moveCart();
		
		});
	
	$(window).resize(function(){
		moveCart();
		
	});
			
	/* search */
	
	$('#wrapper').click(function(){
		$('#suggestions').fadeOut();
	});
	
	$(".viewcart-btn").fancybox({
		'centerOnScroll' : true,
		'width'				: 800,
		'height'			: 500,
        'autoScale'     	: false,
        'autoDimensions' : false,
		'type'				: 'iframe',
		'onClosed' : function(){
		
			refresh_cart();
			
		}
	});
	
	$("#cart_no").fancybox({
						'centerOnScroll' : true,
						'width'				: 800,
						'height'			: 500,
				        'autoScale'     	: false,
				        'autoDimensions' : false,
						'type'				: 'iframe',
						'onClosed' : function(){
						
							refresh_cart();
							
						}
					});
	
	
});

var link = "/site/";

var data_loading = false;

function add_to_cart(id){

	//Show cart
	$('.cart_list').show();
	
	
	// Get the product ID and the quantity 
	//var id = id;
	var qty = 1;
	
	//console.log(id);
	
	if(!data_loading){
	
		data_loading = true;
		
		$('#checkout-btn').hide();
		
		$('#loader').show();
		
		//alert('ID:' + id + '\n\rQTY:' + qty);  

		 $.post(link + "cart/add_cart_item", { product_id: id, quantity: qty, ajax: '1' },
  			function(data){

  			if(data == 'true'){
  			
  				data_loading = false;
  				
  				$('#checkout-btn').show();
  			
  				$('#loader').hide();
  				
  				refresh_cart();
				
				

    		}else{
    			data_loading = false;
    			
    			$('#checkout-btn').show();
  			
  				$('#loader').hide();
    			alert("Product does not exist");
    		}

		//cart_btns();

 		 }); 

		return false;
		
	} else {
	
		alert('Could not add item to cart');
		
	}
	
};

function process_order(){
	window.location = '/dashboard/orders/create';
}

function refresh_cart(){

	var link = "/site/";
			var tsTimeStamp= new Date().getTime();
			$.get(link + "cart/show_cart",{ action: "get", time: tsTimeStamp }, function(cart){
  					$(".cart_list").html(cart);
  					
  					$(".viewcart-btn").fancybox({
						'centerOnScroll' : true,
						'width'				: 800,
						'height'			: 500,
				        'autoScale'     	: false,
				        'autoDimensions' : false,
						'type'				: 'iframe',
						'onClosed' : function(){
						
							refresh_cart();
							
						}
					});
  					
				});
				
			//Show samall
			$.get(link + "cart/show_cart_no",{ action: "get", time: tsTimeStamp }, function(cart){
  					$("#cart_no").html(cart);
  					$("#cart_no").fancybox({
						'centerOnScroll' : true,
						'width'				: 800,
						'height'			: 500,
				        'autoScale'     	: false,
				        'autoDimensions' : false,
						'type'				: 'iframe',
						'onClosed' : function(){
						
							refresh_cart();
							
						}
					});
  					
				});
				
			$('#suggestions').fadeOut();
}

	function update_cart(){
		var id = $(this).parent().find('#fcustomer').val();
		
			//var items = new Array();

			var items = $('#cart_form').serialize();
			
		
		
		//console.log(id);

		var link = "/site/"; 
		
		if(true){
			
				
				
				$('#checkout-btn').hide();
				
				$('#loader').show();

			 $.post(link + "cart/update_cart", { customer_id: id, data: items, ajax: '1' },
	  			function(data){
	
	  			if(data == 'true'){
	  			
	  				
				
					$('#checkout-btn').show();
				
					$('#loader').hide();
	
	    			/*$.get(link + "cart/show_cart", function(cart){
	  					$(".cart_list").html(cart);
					});*/
					
					refresh_cart();
					
	
	
	
	    		}else{
	    			
	    			
					
					$('#checkout-btn').show();
					
					$('#loader').hide();
					
	    			alert("Product does not exist");
	    		}
	
	
	
	 		 }); 
	
			return false;
			
		} else {
			
		}
		
	};

function lookup(inputString) {
   if(inputString.length == 0) {
      $('#suggestions').fadeOut(); // Hide the suggestions box
   } else {
      $.post("/site/searchit/results", {queryString: ""+inputString+""}, function(data) { // Do an AJAX call
         $('#suggestions').fadeIn(); // Show the suggestions box
         $('#suggestions').html(data); // Fill the suggestions box

			//$("#suggestions .add-to-cart").hide();

		$("#suggestions .add-to-cart").click(function() {
			var i = $(this).attr('title');
			add_to_cart(i);
			//console.log($(this).attr('title'));
			
			return false;
		});
		
      });
   }
}

jQuery.clickOrEnter = function(element,callback) {
	jQuery('a').bind('click', function(event) {
  		callback();
  		event.preventDefault(); //prevent browser from following the actual href
	});
	jQuery('a').bind('keypress', function(event) {
		var code=event.charCode || event.keyCode;
		if(code && code == 13) {// if enter is pressed
  			callback();
  			event.preventDefault(); //prevent browser from following the actual href
		};
	});
};

