$(document).ready(function(){	


	function showStock(){
	   var pid = $("#pid").val();
     if ((pid!='') || (pid!=0)) {
		    if($("#stockapi").html() == "") makePOSTRequest("/StockAPI/Stock.php","pid="+pid);
		} else {
				if($("#stockapi").html() == "")  $("#stockapi").html($("#stock_div").html());
		}
	}	

		$("#s_periood").val(24).attr('selected',true);

		$('#bigpic a').fancybox({
		'titlePosition' : 'outside'
		}); 

		$('a[rel=gallery]').fancybox({
			'titlePosition' 	: 'outside',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '<span id="fancybox-title-over">' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
			}
		});
		
		
		
	$('img.smallpic').mouseover(function() {
			var img_src = $(this).attr('src');
			img_src = str_replace("&w=80","&w=225",img_src);
			img_src = str_replace("&h=80","&h=225",img_src);
			$("#img_main").attr("src",img_src);

			var new_href = str_replace("ImageResize.php?src=","",img_src);
					new_href = str_replace("&w=225&h=225","",new_href);
			$("#href_main").attr("href",new_href);

	});


	$("#sissemaksu_suurus").keyup(function () {
			arvuta_kuumaksu();
	});

	$("#stock").click(function () {
			showStock();
	});
	
	$("#tech").click(function () {
			$('#andmed').show();
	});	
	
	$("#links").click(function () {
			$('#lingid').show();
	});	

	$("#info").click(function () {
		$('#kirjeldus').show();
	});		
	/*
	$("#dt-1").click(function () {
			$('#div_uued').show();
	});	
	
	$("#dt-2").click(function () {
			$('#eripakkumised').show();
	});	

	$("#dt-3").click(function () {
		$('#leiunurk').show();
	});		

	*/

	$("#cat-show").click(function () {
		$('.checkout').each(function(index) {
		    //alert(index + ': ' + $(this).attr('id'));

		    $("tr.tr_"+$(this).attr('id')).show();
		    $("#"+$(this).attr('id')).attr('checked','checked');
		    $("tr.tootenimekiri_rida_"+$(this).attr('id')).show();
		    /*
		    //$("tr.tr_"+$(this).attr('id')).hide();
		    $("#"+$(this).attr('id')).checked('checked','checked');
		    */
		});	
		
		
		$("#products-count").html($("#pr-count").val());
		$("#cat-show").show();
		$("tr.cat-list").hide();
		
		
	});	


	
	$("a.ajax-button").click(function () {

		var id = str_replace('ID_','',$(this).attr('id'));
		var arr = new Array();
		
		arr['searchcode'] = id;
		arr['quantity'] = $("input[name=korv_x["+id+"]]").val();
		
		$.ajax({
    url: "inc/basket.php",
    type: "POST",
    timeout: 20000,
    data: { 
			basket: [ id, $("input[name=korv_x["+id+"]]").val()]
		},
		
    cache: false,
    beforeSend: function() {

        $.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff' 
        } }); 


    },
    success: function (data) {   
    
			setTimeout($.unblockUI, 0); 
			$("#basket-info").html(data);
    },
		error: function(xhr, textStatus, errorThrown){
			setTimeout($.unblockUI, 0); 
			$("#basket-info").html('<br /><font color="red">Viga toote lisamisel. Palun proovige uuesti.</div>');
		}
	});
	return false;
});




			
	
	$(".checkout").click(function () {		
		if ($("tr.tootenimekiri_rida_"+$(this).attr('id')).is(":visible")==true) {
			$("tr.tootenimekiri_rida_"+$(this).attr('id')).hide();
		} else {
			$("tr.tootenimekiri_rida_"+$(this).attr('id')).show();
		}		
	});	
	
	

$(document).ready(function() 
    { 
        $("#searchTable").tablesorter(); 
    } 
); 
	
	$("#show_stock").click(function () {

    var arrDivs = [ "kirjeldus", "andmed", "lingid", "laoseis"];
    var arrTabs = [ "info", "tech", "links", "stock"];
    jQuery.each(arrDivs, function() {
      $("#" + this).hide();
   });

    
    jQuery.each(arrTabs, function() {
      $("#" + this).attr('class','');
      
   });
			showStock();
			$("#stock").attr('class','selected');
			$("#laoseis").css('display','block');
	});		

	if ($('#news-slider').html()!=null) {
		$('#news-slider') 
		.before('<div id="nav">') 
		.cycle({ 
		    fx:     'fade', 
		    speed: 2000,
		    pause: 6,
		    timeout: 5000,
		    pager:  '#nav' 
		});		
	}

	
	$("#slider").easySlider({
		auto: true, 
		continuous: true,
		speed: 800,
		pause: 8000,
		numeric: true
	});
		$("#slider2").easySlider({
     
     continuous: true,
     prevId: 'prevBtn2',
     nextId: 'nextBtn2'	
  });			
  	$("#slider3").easySlider({
     
     vertical: true,
     continuous: true,
     prevId: 'prevBtn3',
     nextId: 'nextBtn3'	
  });	
  $("#slider4").easySlider({
     
     
     continuous: true,
     prevId: 'prevBtn4',
     nextId: 'nextBtn4'	
  });					


$("#regForm").validate({ 

submitHandler: function(form) {
$("#err").fadeOut("slow");
$.ajax({
    url: "inc/reg.php",
    type: "POST",
    timeout: 20000,
    data: { 
			username: $("input[name=username]").val(),
			company: $("input[name=nimetus]").val(), 
			regcode: $("input[name=regno]").val(), 
			email: $("input[name=email]").val(),
			firstname: $("input[name=ees_nimi]").val(),
			lastname: $("input[name=pere_nimi]").val(),
			password: $("input[name=parool]").val(),
			address: $("input[name=aadress]").val(),
			zip: $("input[name=linn]").val(),
			newsletter: $("input:radio[name=soodus]:checked").val(),
			phone: $("input[name=telefon]").val()
		},
		
    cache: false,
    beforeSend: function() {
    	$("#failed").html("<img src='http://test.opood.ee/Images/loading.gif'>");
      $("#failed").show("fast");
    },
    success: function (data) {   
			if (data==0) {
				$("div.special").html('<div class="notice"><b>Registreerumine edukas! Täname!</b><br /><br /> Teie e-mailile saadeti registreerumise kinnitus. Sealt leiate juhised, kuidas kasutajakonto aktiveerida.</div>');
				$("body").animate({scrollTop:0}, "slow");//IE, FF
				$("html").animate({scrollTop:0}, "slow")
      } else {
				$("#err").fadeIn("slow");
				$("#failed").hide("fast");
				$("#err").html(data);
				$("body").animate({scrollTop:0}, "slow");//IE, FF
				$("html").animate({scrollTop:0}, "slow")

			}
			
    },
		error: function(xhr, textStatus, errorThrown){
 		$("#failed").html("Registreerimine ei õnnestunud. Palun proovige uuesti.");
	}

});
	},

  rules: { 
    email: {
    required: true, 
    email: true 
  },
	username: { 
	  required: true
  },
  ees_nimi: { 
    required: true
  },
  pere_nimi: { 
    required: true
  },
  aadress: {
		required: true
	},
	linn: {
		required: true											 
	},
	regno: {
		digits: true
	},
	
	aadress: {
		required: true											 
	},
	telefon: {
		required: true											 
	},
	parool: {
		required: true,		
		minlength: 3									 
	},
	parool2: {
		equalTo: "#psword"												 
	}
},
messages:
{
    parool:
    {
      minlength: "Parooli pikkus peab olema vähemalt 3 tähemärki"
    },
    parool2:
    {
			equalTo: "Paroolid ei kattunud"
		}
}




}); 





$("#liisiForm").validate({ 
submitHandler: function(form) {
$.ajax({
    url: "inc/process.php",
    type: "POST", 
    data: { 
			firstname: $("input[name=eesnimi]").val(),
			lastname: $("input[name=perenimi]").val(), 
			idcode: $("input[name=isikukood]").val(), 
			phone: $("input[name=telefon]").val(), 
			email: $("input[name=email]").val(), 
			adr1: $("input[name=aadress]").val(),
			adr2: $("input[name=linn]").val(),
			adr3: $("select[name=maakond]").val(),
			adr4: $("input[name=postiindeks]").val(),
			employer: $("input[name=firma]").val(),
			occupation: $("input[name=amet]").val(),
			time: $("select[name=staaz]").val(),
			salary: $("select[name=palk]").val(),
			duration: $("select[name=periood]").val(),
			payday: $("select[name=maksepaev]").val(),
			paydown: $("input[name=sissemakse]").val(),
			orderid: $("input[name=tellimuse_number]").val()	
		},
    cache: false,
    beforeSend: function() {
    $("#btn").hide("fast");
    $("#status").html($("#img_loading").html()).show("fast");
    },
    success: function (data) {   
    $("#btn").show("fast");
    $("#status").hide("fast");
				if (data==1) {
						$("#liisi").html($("#complete").html());
						$("body").animate({scrollTop:0}, "slow");//IE, FF
						$("html").animate({scrollTop:0}, "slow");										
				} else {
						$("#status").html(data).fadeIn("fast");
				}
				
    },
		error: function(xhr, textStatus, errorThrown){
 		$("#status").html($("#failed").html());
 		$("#btn").fadeIn("fast");
		}		
		
		 
});



	},

  rules: { 
    email: {
    required: true, 
    email: true 
  }, 
  perenimi: { 
    required: true
  }, 
  isikukood: { 
    required: true,
		digits: true
  },
  eesnimi: { 
    required: true
  },
  aadress: { 
    required: true 
  },
  linn: { 
    required: true 
  },
	postiindeks: {
		required: true,
		digits: true		
	},
	telefon: {
		required: true
	},
	firma: {
		required: true
	}, 
	amet: {
		required: true
	},
	sissemakse: {
		required: true,
		min: $("#t_min").val()
	},
	kuumakse: {
		required: true,
		min: 7
	}																 
},
messages:
{
    kuumakse:
    {
      min: "Minimaalne kuumakse 7 EUR"
    }
}




}); 



	
});

ddaccordion.init({
	headerclass: "silverheader", //Shared CSS class name of headers group
	contentclass: "submenu", //Shared CSS class name of contents group
	revealtype: "mouseover", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false
	defaultexpanded: [0], //index of content(s) open by default [index1, index2, etc] [] denotes no content
	onemustopen: true, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: true, //persist state of opened contents within browser session?
	toggleclass: ["", "selected"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})


