$(document).ready(function(){
	if(screen.width > 1024){
		$(".container").css({padding:"0 20px"});
		$(".main_container").css({width:"1040px"});
	}
	// ajax p2ringute seaded///////////////////////
	$.ajaxSetup({
	  cache: true,
	  timeout: 10000, //10s
	  error:function(x,e){
		var msg;
		if (x === null){
		      msg = 'no connection?\n';
		} else {
		      if(x.status==0){
			      msg = 'You are offline!\nPlease check your network connection.';
		      }else if(x.status==404){
			      msg = 'Requested URL not found.';
		      }else if(x.status==500){
			      msg = 'Internal Server Error.';
		      }else if(e=='parsererror'){
			      msg = 'Error.\nParsing JSON Request failed.';
		      }else if(e=='timeout'){
			      msg = 'Request time out.\nPlease try again.';
		      }else {
			      msg = 'Unknown error.\n'+x.responseText;
		      }
		}
		alert(msg);
	      }
	});	
	///////////////////////////////
	forms([
			{form: ".search form"},
			{form: ".find_medicine form"},
			{form: ".quiz form"},
			{form: ".login form", type:"simple"},
			{form: ".find_doctor form"},
			{form: ".newsletter form"},
			{form: ".long_input form"},
			{form: ".gunekoloog form"}
			]);
	
	// fails, kus see vorm on 14.01.10.
	//validate_form({form:".add_kyss form"});
	///////////////// popup lingid, mis l2hevad notification'i sisse ///////////
	$(".ajax_popup").click(function() {
	    var ob = $(this);
	    ob.attr("disabled", "true");
	    $.ajax({
			type: "GET",
			url: $(this).attr('href'),
			data: '_ajax=content',
			success: function(msg){
				$("#ajax_popup_div").empty().html(msg);
				ob.attr("disabled", "false");
			}
	     });
	    return false;
	});
});

function forms( options ){
	for(var c=0; c < options.length; c++){
		
		if($(options[c].form).attr("method")){
		
			$(options[c].form+" input").each(function(){
				$(options[c].form)[0].reset(); 									
				var value = $(this).val();
				var type = $(this).attr("type");
	
				
				
				$(this).focus(function(){
					if($(this).attr("type") == "submit") return false;	  
					if($(this).val() == value){
						$(this).val("");
					}
				});
				
				$(this).blur(function(){
					$(this).val().length == 0 ? $(this).val(value) : "";
				});
				
			});//each
			
		}//if
	} //for
}


function validate_form(options){
	/*
	usage:	validate_form({form:" selector "});    the forms ID or CLASS
				category="validate"							to validate fields
				type="email"  									if it is an EMAIL field
				min="5"											to set the MINIMUM required characters
				max="5"											to set the MAXIMUM amount of characters
				
				
				.error 											that is the DEFAULT error class name
	
	by Henri Kokk
		www.henri.ee
	*/
	if($(options.form).find("input").attr("name") !== null){
		
		var o = {
			type: "category",
			btn:	"saada",
			err_class: "error",
			object: options.form
		};
		
		$("[rel='validate']").keyup(function(e){
			if(e.keyCode == 9) return false;
			validates($(this));
		});
		$("[rel='validate']").click(function(){
			if($(this).attr("type") == "radio"){validates($(this));}
			if($(this).attr("type") == "checkbox"){validates($(this));}
		});
		
		$(o.object).submit(function(){
			o.counter=0;
			$(o.object).find("[rel='validate']").each(function(){
				$(this).parents(".label").removeClass(o.err_class);
				validates($(this));
				$(this).parents(".label").attr("class").indexOf(o.err_class) != -1 ? o.counter++ : "";
				
			});
			if(o.counter == 0) {
			    if(!$(o.object).attr('no_ajax')) {
					var formData = $(o.object).serialize();
					formData += '&_ajax=content';
					$.ajax({
						 type: "POST",
						 url: $(o.object).attr('action'),
						 data: formData,
						 success: function(msg){
							$(".inside").html(msg);
						 }
					   });
				} else {
					return true;
			    }
			}
			
			return false;
			
		});
	}
	
	function validates(obj){
		if(obj.attr(o.type) == "email"){
			check_mail(obj.val()) == false ? obj.parents(".label").addClass(o.err_class): obj.parents(".label").removeClass(o.err_class);
		}
		else if(obj.attr("type") == "radio"){
			$("[name='"+obj.attr("name")+"']:checked").val() ? $(obj).parents(".label").removeClass("error") : $(obj).parents(".label").addClass("error");			
		}
		else if(obj.attr("type") == "checkbox"){
			obj.is(':checked') ? $(obj).parents(".label").removeClass("error") : $(obj).parents(".label").addClass("error");			
		}
		else{
			o.minimum = $(obj).attr("min") || 1;
			o.maximum = $(obj).attr("max") || 9999999999;
			obj.val().length < o.minimum ? obj.parents(".label").addClass(o.err_class) : obj.parents(".label").removeClass(o.err_class);
			obj.val().length > o.maximum ? obj.val(obj.val().substring(0, o.maximum)) : "";
		}
		
	}
	
	function check_mail(emailAddress) {
		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
		return pattern.test(emailAddress);
	}
}
   
function notification( options ){
	
	var o ={};
	o.text = options['text'] || 'This is a demo text';
	o.fade = options['fade'] || 'true';
	o.rainbow = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
	o.t_layer = options['t_layer'] || 'true';
	o.t_lvl = options['t_lvl'] || '0.5';
	o.t_color = options['t_color'] || '#000';
	o.delay = options['delay'] || '3000';
	o.speed = options['speed'] || '2000';
	o.clickTAG = options['clickTag'] || '.notification';
	o.type = options['type'] || 'default';
	o.id = 'notification';
	o.flag = 'true';
	o.scroller = "true";
	if(options.t_color == "rainbow"){o.t_color = o.rainbow;}
	
	o.html = '<div class="notification" id="'+o.id+'">';
	o.html+= '<div class="top">&nbsp;</div><div class="middle">';
	o.html+= o.text;
	o.html+= '</div>';
	o.html+= '<div class="bottom">&nbsp;</div>';
	o.html+= '</div>';
	
	$(o.clickTAG).click(); //vana aken enne kinni;
	$("body").append(o.html);  

	if($(".notification").outerHeight() > $(window).height()-50){$(".notification").css({position:"absolute"}); o.scroller="false";}
	if($(".notification").css("position") == "absolute" && o.scroller == "true"){$(window).scroll(positions);}
	positions(false);
	function positions( switcher ){
		if(o.flag == "true"){
			var pos = {};
			pos.left = ($(window).width() - $("#"+o.id).outerWidth())/2;
			pos.top = $(window).scrollTop() + (($(window).height() - $("#"+o.id).outerHeight())/2);
	
			if(pos.top <0 || $(".notification").outerHeight() > $(window).height()-50){
				pos.top = $(window).scrollTop()+50;
			}
			
			if($(".notification").css("position") == "fixed"){
				pos.top = (($(window).height() - $("#"+o.id).outerHeight())/2);
			}
			
			if(switcher == false){
				$("#"+o.id).css({'left':pos.left+'px', 'top':pos.top+'px'});
			}
			
			else{
				$("#"+o.id).animate({'left':pos.left+'px', 'top':pos.top+'px'},{duration:300, queue:false});
			}
			
		}
	}
	if(o.t_layer == "true"){
      $("body").append('<div class="opaque" id="opaque_'+o.id+'">&nbsp;</div>');
      $("#opaque_"+o.id).css({'position':'absolute', 'top':'0px', 'z-index':'900', 'left':'0px','background':o.t_color, 'height':$(document).height()+'px', 'width':$(document).width()+'px'}).fadeTo(0, o.t_lvl);
	}
	if(o.fade == "true"){fade_out(o.delay)}
   else{
      $(o.clickTAG).click(function(){fade_out(0);});
      $(o.clickTAG).css({'cursor':'pointer'});
   }
   function fade_out( delay ){
      $("#"+o.id).fadeTo(delay, "1.0").fadeOut(o.speed, function(){$(this).remove();});
      if(o.t_layer == "true"){
         $("#opaque_"+o.id).fadeTo(delay, o.t_lvl).fadeOut(o.speed, function(){$(this).remove();});
      }
		o.flag = "false";
   }
}

