$(document).ready(function(){

		// --- external links ---
		$('a[rel$="external"]').click(function(){
				this.target = "_blank";
		});


		// --- shoping cart ---
		
		  $.get("/managecart.php",
         function(data){       
           $("form#shopcart").html(data).show();        
      });
		
		
     $.listen('click','a.addcart',function(){
								
        $("div#p"+$(this).attr('id')).css({ display: "block"}),
        $("div#p"+$(this).attr('id')+" b").text(parseInt($("div#p"+$(this).attr('id')+" b").text())+1),
        //$("a#"+$(this).attr('id')).css({ display: "none"}),
        $("div#sz"+$(this).attr('id')).css({ display: "none"}),
        
        $.get("/managecart.php", { item: $(this).attr('id'), task: "add" },
          function(data){       
            $("form#shopcart").html(data).show();        
          });
      });
      
      
      $.listen('click','a.shop-add',function(){
        
        $("div#p"+$(this).attr('prp')+" b").text(parseInt($("div#p"+$(this).attr('prp')+" b").text())+1),
        
        $.get("/managecart.php", { item: $(this).attr('prp'), task: "add" },
          function(data){       
            $("form#shopcart").html(data).show();        
          });
      });
      
      
      $.listen('click','a.shop-rem',function(){
        
        prid = $(this).attr('prr');
        count=parseInt($("div#p"+prid+" b").text())-1;
        
        
        if(count<1){
        	
        	$("div#p"+prid+" b").text('0');
        	$("div#p"+prid).css({ display: "none"});
 		    	$("div#sz"+prid).css({ display: "block"});
        
        }else{
        	
        	
        	$("div#p"+$(this).attr('prr')).css({ display: "block"});
        	$("div#p"+$(this).attr('prr')+" b").text(count);
        }
        
        $.get("/managecart.php", { item: $(this).attr('prr'), task: "remove" },
          function(data){       
            $("form#shopcart").html(data).show();        
          });
      });
      
      
      $.listen('click','a.shop-del',function(){
        
        
        $("div#p"+$(this).attr('prd')+" b").text('0'),
        $("div#p"+$(this).attr('prd')).css({ display: "none"}),
        
        
        $("div#sz"+$(this).attr('prd')).css({ display: "block"}),
        
        $.get("/managecart.php", { item: $(this).attr('prd'), task: "del" },
          function(data){       
            $("form#shopcart").html(data).show();        
          });
      });
      

      $('.order').click(function(){ 
            location.href='/order_confirm.php'; 
      }); 

      $("input.order").hover(function () {
          $(this).addClass('hovered_buton');
      }, function () {
          $(this).removeClass('hovered_buton');
      });

      $("input.submit").hover(function () {
          $(this).addClass('hovered_buton');
      }, function () {
          $(this).removeClass('hovered_buton');
      });




		// --- check email function ---
		function isValidEmail(email_string){
		
				var email_expression = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
				if(email_expression.test(email_string)) {
					return true;
				}else{
					return false;
				}
		
		}

		// --- Promotions slider ---
		function onBefore() {
		
				var promo_url = $(this).children('img').attr('id');
				var price = $(this).children('img').attr('price');
				
		    $('a.buy').attr('href', '/products/' + promo_url + '.html').children('span').html(price);
		    $('a.details').attr('href', '/products/' + promo_url + '.html');
		    
		}

		$('#promoslider').after('<div id="nav">').cycle({
	/* 			fx:     'blindX', */ 
				speed: 1500,
		    timeout: 6000,
		    pause: 1,
		    pager:  '#nav',
		    next:   '#next', 
				prev:   '#prev',
				before:  onBefore					
		});
		
		// --- Quick Registration Modal -- 
		
		$('#qreg').click(function(){
				$('#quick_register').load('/register_quick.php').dialog('open');
		});
		
		$('#quick_register').dialog({
				autoOpen: false,
				width: 450,
				height: 500,
				modal: true,
				buttons: { 
					"РЕГИСТРИРАЙ МЕ": function() { 
							var username 	= $('#luser'),
									password 	= $('#lpass'),
									names  		= $('#lnames'),
									phones  	= $('#lphones'),
									captcha  	= $('#captcha');
									
							if(!isValidEmail(username.val())){
								$('p#errorlogin').text('Моля, въведете валиден email адрес').effect('highlight', {}, 1000);
							}else if(password.val().length < 6){
								$('p#errorlogin').text('Моля, въведете валидна парола. Минимум 6 символа дължина.').effect('highlight', {}, 1000);
							}else if(names.val().length < 6){
								$('p#errorlogin').text('Моля, въведете вашите имена. Минимум 6 символа дължина.').effect('highlight', {}, 1000);
							}else if(phones.val().length < 4){
								$('p#errorlogin').text('Моля, въведете валиден телефонен номер.').effect('highlight', {}, 1000);
							}else if(captcha.val().length < 5){
								$('p#errorlogin').text('Моля, въведете 5 буквения код от картинката').effect('highlight', {}, 1000);
							
							}else{
							
									$.ajax({
								   type: "POST",
								   async: false,
								   url: "/register_quick.php",
								   data: "captcha="+captcha.val()+'&useremail='+username.val()+'&userpass='+password.val()+'&usernames='+names.val()+'&userphones='+phones.val(),
								   success: function(ajaxresult){

								   
								     if(ajaxresult == 'ok'){
								     			
								     			$('p#errorlogin').text('Регистрация на ' + username.val() + '...').animate({ backgroundColor: "#e1e9f9" }, 700, function(){
								   						
								   						
								   						$.ajax({
														   type: "POST",
														   async: false,
														   url: "/login_post.php",
														   data: "captcha="+captcha.val()+'&loginuser='+username.val()+'&loginpass='+password.val(),
														   success: function(ajaxresult){
						
														   
								     			
														     			$('p#errorlogin').text('Добре дошли, ' + names.val() + '...').animate({ backgroundColor: "#e1e9f9" }, 700, function(){
														     					window.location.reload();
														     			});
														     																	     			
														     			
														     
														     
														   }
														
								   						});
								     			});
								     			
								     			
								     			
								     }else{
								     
								     		password.val('');
								     		captcha.val('');
								     		var rand_no = Math.random();
												rand_no = rand_no * 100;
												rand_no = Math.ceil(rand_no);
								     		$('#captchaimg').attr('src', '/captcha.php?q='+rand_no);
								     		$('p#errorlogin').text(ajaxresult).effect('highlight', {}, 1000);
								     
								     }
								     
								     
								   }
								 });
							
									
							
							}		
					} 
				}
		});
		
		// --- Users Login Modal ---
		
		$('.enter').click(function(){
				$('#vhod').load('/login_form.php').dialog('open');
		});
		
		
		
		$('#vhod').dialog({
				autoOpen: false,
				width: 450,
				height: 410,
				modal: true,
				buttons: { 
					"ВХОД": function() { 
							var username = $('#luser'),
									password = $('#lpass'),
									captcha  = $('#captcha');
									
									
							if(!isValidEmail(username.val())){
							
								$('p#errorlogin').text('Моля, въведете реален email адрес').effect('highlight', {}, 1000);
							
							}else if(password.val().length < 1){
							
								$('p#errorlogin').text('Моля, въведете парола.').effect('highlight', {}, 1000);
							
							}else if(captcha.val().length < 5){
								
								$('p#errorlogin').text('Моля, въведете 5 буквения код от картинката').effect('highlight', {}, 1000);
							
							}else{
							
									$.ajax({
								   type: "POST",
								   async: false,
								   url: "/login_post.php",
								   data: "captcha="+captcha.val()+'&loginuser='+username.val()+'&loginpass='+password.val(),
								   success: function(ajaxresult){

								   
								     if(ajaxresult == 'ok'){
								     			
								     			$('p#errorlogin').text('Добре дошли, ' + username.val() + '...').animate({ backgroundColor: "#e1e9f9" }, 500, function(){
								     					window.location.reload();
								     			});
								     			
								     			
								     			
								     }else{
								     
								     		password.val('');
								     		captcha.val('');
								     		var rand_no = Math.random();
												rand_no = rand_no * 100;
												rand_no = Math.ceil(rand_no);
								     		$('#captchaimg').attr('src', '/captcha.php?q='+rand_no);
								     		$('p#errorlogin').text(ajaxresult).effect('highlight', {}, 1000);
								     
								     }
								     
								     
								   }
								 });
							
									
							
							}		
					} 
				}
		});



		// --- Expandable Categories ---
		 
			$('ul.main > li > a').click(function(){ 

					$('ul.main > li > a').not(this).next('ul.sub').slideUp().end().not(this).removeClass('active');
          $(this).addClass('active');
          $(this).next('ul.sub').slideDown();
          return false;
          
      });
      
    // --- Gallery Window ---
    if($("a.prgal").length > 0){
				$('a.prgal').lightBox();
		}
		
		$('#mainproductimg').live('click', function(){
		
				$('.gallerybutton').click();
				return false;
		
		});
		
		function ltrim(str){
        return str.replace(/^\s+/, '');
    }
    function rtrim(str) {
        return str.replace(/\s+$/, '');
    }
    function alltrim(str) {
        return str.replace(/^\s+|\s+$/g, '');
    }	
		
		// --- Search Products ---
		$('#searchlink').live('click', function(){
		
				var searchstring = $('#searchfield').val();
				searchstring = jQuery.trim(searchstring);
				if(searchstring != ''){
					var myNewString = searchstring.replace(/\s+/g, '+');
					var redir = '/search/' + myNewString + '/';
					window.location.href = redir;
				}else{
					alert('Моля, въведете текст за търсене!');
					$('#searchfield').focus();
				}
				return false;
		
		});
		
		$('#searchfield').bind('keypress', function(e){
				if(e.keyCode == 13) $('#searchlink').click();
		});

		
});