jQuery(document).ready(function(){
	accordMenu();
	if(jQuery('#article-cont').length > 0){
		cols();
		resizeFont();
	}
	if(jQuery('#art_gallery a').length > 0){
		imgViewer();
	}
	if(jQuery('div.add_comment').length > 0){
		setCommentLink();
	}
	if(jQuery("ul.cal-list").length > 0){
		setCommentSlider();
	}
	if(jQuery("#tabnav").length > 0){
		setArticleTabs();
	}
	
	jQuery('div.big-article img, div.normal-article img').jcaption({
		copyStyle: true,
		animate: true,
		show: {height: "show"},
		hide: {height: "hide"}
	});
	
	makeVoting();
});

jQuery.fn.fadeTo = function(speed,to,callback) { 
    return this.animate({opacity: to}, speed, function() { 
        if (to == 1 && jQuery.browser.msie)  
            this.style.removeAttribute('filter');  
        if (jQuery.isFunction(callback)) 
            callback();  
    }); 
};

/* accordation menu */
function accordMenu(){
	jQuery("#rightMenu .rContent").hide();
	jQuery("#rightMenu .body-kusi_teadlaselt").show();
	
	jQuery('#rightMenu .rHeading').click(function() {
		jQuery('#rightMenu .rContent').slideUp('normal');
		jQuery(this).next().slideDown('normal');
	});
	
}

/* Hide 2 cols in article view */
function cols(){
	var cols = jQuery('div.leftSide,div.rightSide');

	cols.fadeTo("fast", 0.10); 
		
	cols.hover(
		function() {// hover state
			cols.fadeTo("fast", 1.0);
		},
		function() { // back to off
			cols.fadeTo("fast", 0.10); 
		}
	);
}

/* Font resize */
function resizeFont(){
	// Increase Font Size
	jQuery(".increaseFont").click(function(){
		tags = new Array ( "p", "li", "h2", "h3", "h4", "h5", "h6", "td", "tr", "div", "span", "input", "textarea", "option", "select", "a");
		for (j=0; j<tags.length; j++) {
			var currentFontSize = jQuery('#article-cont '+tags[j]).css('font-size');
			
			if(currentFontSize!=undefined){
				var currentFontSizeNum = parseFloat(currentFontSize, 10);
				var newFontSize   = currentFontSizeNum+1;
				if(newFontSize<=17){
					jQuery('#article-cont '+tags[j]).css('font-size', newFontSize);
				}
			}
		}
		return false;
	});
	
	// Decrease Font Size
	jQuery(".decreaseFont").click(function(){
		tags = new Array ( "p", "li", "h2", "h3", "h4", "h5", "h6", "td", "tr", "div", "span", "input", "textarea", "option", "select", "a");
		for (j=0; j<tags.length; j++) {
			var currentFontSize = jQuery('#article-cont '+tags[j]).css('font-size');
			
			if(currentFontSize!=undefined){
				var currentFontSizeNum = parseFloat(currentFontSize, 10);
				var newFontSize   = currentFontSizeNum-1;
				if(newFontSize>=9){
					jQuery('#article-cont '+tags[j]).css('font-size', newFontSize);
				}
			}
		}
		return false;
	});
}

/* Gallery functions */
function imgViewer(){
	var i = 1;
	var images = jQuery('a.gal');
	
	//lets set img count 
	jQuery('#imgviewer_pics').text(i+'/'+images.length);
	
	var OrigSmallImg = jQuery('#pic_'+i+' img').attr('src');
	
	//if user clicks next
	jQuery('#imgviewer_next').click(function(){
		i++;
		
		//console.log(images.length);
		//console.log((i-1));
		
		if((i-1)==(images.length)){i=1;}
		
		var smallImgUrl = jQuery('#pic_'+i+' img').attr('src');
		//var BigImgUrl = jQuery('#pic_'+i).attr('href');
		var imgSignData = jQuery('#pic_'+i).attr('title');
		var imgSignAuthor = jQuery('#pic_'+i+' img').attr('alt');
		
		if(i == 1){
			jQuery('#articleimg').attr('src', OrigSmallImg);
		}else{
			jQuery('#articleimg').attr('src', smallImgUrl);
		}
		
		//jQuery('#pic_1').attr('href', BigImgUrl);
		jQuery('#articleimg').attr('title', imgSignData);
		jQuery('#imgviewer_sign .imgviewer_sign_data').html(imgSignData);
		jQuery('#imgviewer_sign .imgviewer_sign_author').html(imgSignAuthor);
		
		jQuery('#imgviewer_pics').text(i+'/'+images.length);
	});
	
	jQuery('#imgviewer_back').click(function(){
		i--;		
		if(i == 0) {i=images.length;}
		
		var smallImgUrl = jQuery('#pic_'+i+' img').attr('src');
		//var BigImgUrl = jQuery('#pic_'+i).attr('href');
		var imgSignData = jQuery('#pic_'+i).attr('title');
		var imgSignAuthor = jQuery('#pic_'+i+' img').attr('alt');
		
		jQuery('#articleimg').attr('src', smallImgUrl);
		//jQuery('#pic_1').attr('href', BigImgUrl);
		jQuery('#articleimg').attr('title', imgSignData);
		jQuery('#imgviewer_sign .imgviewer_sign_data').html(imgSignData);
		jQuery('#imgviewer_sign .imgviewer_sign_author').html(imgSignAuthor);
		jQuery('#imgviewer_pics').text(i+'/'+images.length);
	});
	
	jQuery('#art_gallery a').lightBox({txtImage:'',txtOf:'/'});
}

/* comment link function */
function setCommentLink(){
	var commnetLink = jQuery('div.add_comment');
	
	commnetLink.fadeTo("fast", 0.10);
	
	jQuery.each(commnetLink, function() {
		var display_timeout = 0;

		jQuery(this).hover(
			function() {// hover state'
				if(display_timeout != 0) {
					clearTimeout(display_timeout);
				}
				
				var this_element = this;
				
				display_timeout = setTimeout(function() {
					display_timeout = 0;
					jQuery(this_element).fadeTo("fast", 1.0);
				}, 200);
			},
			function() { // back to off
				if(display_timeout != 0) {
					clearTimeout(display_timeout);
				}
				jQuery(this).fadeTo("fast", 0.10);
			}
		);
	});
}
function setCommentSlider(){
	jQuery("a.ev_clikable").click( function(){
		var ids = jQuery(this).attr('id');
		if(ids.length > 0){
			jQuery("div.event-desc").slideUp(600);
			jQuery('div.'+ids).slideToggle(600);
			updateEventCount(ids);
		}
		return false;
	});
}

function updateEventCount(ids){
	var arrPaths = window.location.href.split('ET'); 
	var url = arrPaths[0];

	var arr = ids.split('_');
	
	
	var toUpdate = arr[1];
	
	jQuery.ajax({
	  url: 		url+"popup.php?act=updateEvent",
	  type:		'POST',
	  cache: 	false,
	  data:		'eventID='+toUpdate,
	  success: 	function(resp){
	    			jQuery('div.viewed_'+toUpdate).html(resp);
	  		}
	});
}

function setArticleTabs(){	
	jQuery("#tabnav a").click(function(){
		jQuery("#tabnav a").attr('id',"");
		
		jQuery(this).attr('id',"tabnavActive");
		jQuery(this).focus();
		
		var hre = jQuery(this).attr('href');
		var ids = hre.substr(1);
		
		jQuery("#tabnav_content").children().slideUp(400);
		jQuery("#"+ids).slideDown(500);	
		
		return false;
	});
}


function sendClueSubmit(url){
	var clue = jQuery('#comment_val').val();
	var email = jQuery('#email').val();
	
	if(clue.length > 0){
		if(validEmail(email)){
			jQuery.ajax({
			  url: 		url+"popup.php?act=SaveClue",
			  type:		'POST',
			  cache: 	false,
			  data:		'email='+email+'&clue='+clue,
			  success: 	function(resp){
			    			jQuery('div.con').html(resp);
			    			setTimeout(
			    				function(){ 
			    					tb_remove();
			    					
			    				}, 1500
			    			);
			  		}
			});
		}else{
			alert("Palun sisestage korrektne epost!");
		}
	}else{
		alert("Palun sisestage vihe!");
	}
}


function sendToFriend(url,tid){
	var fromName  = jQuery("#from_name").val();
	var fromEmail = jQuery("#from_email").val();
	var toName    = jQuery("#to_name").val();
	var toEmail   = jQuery("#to_email").val();
	var comment   = jQuery("#comment_val2").val();
	
	if(fromName.length > 0 && fromEmail.length > 0 && toName.length > 0 && toEmail.length > 0){
		if(validEmail(fromEmail) && validEmail(toEmail)){
			jQuery.ajax({
			  url: 		url+"popup.php?act=sendArticle",
			  type:		'POST',
			  cache: 	false,
			  data:		'fromName='+fromName+'&fromEmail='+fromEmail+'&toName='+toName+'&toEmail='+toEmail+'&comment='+comment+'&articleID='+tid,
			  success: 	function(resp){
						jQuery('#con').html(resp);
			    			setTimeout(
			    				function(){ 
			    					tb_remove();
			    					
			    				}, 2000
			    			);
			  		}
			});
		}else{
			jQuery("div.commentMessages").html("<div class='error'>Ebakorrekne e-post!</div>");
			jQuery("div.commentMessages").show('slow');
		}
	}else{
		jQuery("div.commentMessages").html("<div class='error'>Palun täitke kõik väljad!</div>");
		jQuery("div.commentMessages").show('slow');
	}
}



function validEmail(email){      
	var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	return emailReg.test(email); 
}

function setComment(url,tid,boolVideo){
	var Personname = jQuery('#comment_name').val();
	var Personemail = jQuery('#comment_email').val();
	var PersonComment = jQuery('#comment_val').val();
	var PersonPubEmail = jQuery('#comment_email_public:checked').val();
	
	var Quoted = jQuery('#quoted').val();
	
	var messDiv = jQuery('div.commentMessages');
	
	if(Personname.length > 0 && Personemail.length > 0 && PersonComment.length > 0){
		if(validEmail(Personemail)){
			jQuery.ajax({
			  url: 		url+"popup.php?act=setComment",
			  type:		'POST',
			  cache: 	false,
			  contentType:  "application/x-www-form-urlencoded;charset=ISO-8859-1",
			  data:		'name='+Personname+'&email='+Personemail+'&comment='+PersonComment+'&pub_email='+PersonPubEmail+'&tid='+tid+'&quoted='+Quoted+'&video='+boolVideo,
			  success: 	function(msg){
						if(Quoted!='undefined' && Quoted!=undefined){
							jQuery("#lisa_kommentaar_quoted").hide('slow');
							jQuery('div.quoted-mess').html(msg);
							jQuery('div.quoted-mess').show('slow');
						}else{
							messDiv.html(msg);
							messDiv.show('slow');
							
							setRealTimeUpdate(Personname,Personemail,PersonComment,PersonPubEmail);
							
							jQuery('#comment_name, #comment_email, #comment_val').val("");
						}
			  		}
			});
		}else{
			messDiv.html("<div class='error'>Ebakorrekne e-post!</div>");
			messDiv.show('slow');
		}
	}else{
		messDiv.html("<div class='error'>Palun täitke kõik väljad!</div>");
		messDiv.show('slow');
	}
}

function setRealTimeUpdate(Personname,Personemail,PersonComment,PersonPubEmail){
	var nr = jQuery("span.countComments").html();
	//Lets update comment number
	jQuery("span.countComments").html((nr*1)+1);
	
	var currentTime = new Date()
	
	var day = currentTime.getDate();
	var month = currentTime.getMonth() + 1;
	var year = currentTime.getFullYear();
	
	var hour = currentTime.getHours();
	var minute = currentTime.getMinutes();
	
	var curr = day+"."+month+"."+year+" "+hour+":"+minute;
	
	if(PersonPubEmail!=undefined && PersonPubEmail!='undefined' ){
		var email = Personemail;
	}else{
		var email = "";
	}

	
	var htm = "<div class='article-comment'><div class='orange size11'>"+curr+"</div><div class='commentator'><span class='darkgrey'>"+Personname+"</span> "+email+"</div><p>"+PersonComment+"</p><div class='borderBottom'></div></div>";
	
	jQuery("#article_comments").append(htm);
	
	
}

function setQuotedComment(url,CommentID,artID){
	jQuery.ajax({
		url: 	url+"popup.php?act=getCommentBox",
	  	type:	'POST',
	  	cache: 	false,
	  	data:	'commentID='+CommentID+'&articleID='+artID,
	  	success: function(resp){
	  			jQuery('#quoted_comment_'+CommentID).hide();
	  			jQuery('#quoted_comment_'+CommentID).html(resp);
	  			jQuery('.id-'+CommentID).hide();
	  			jQuery('#quoted_comment_'+CommentID).show('slow');
	  		}
	});
}

function setQuotedComment2(url,CommentID,artID){
	jQuery.ajax({
		url: 	url+"popup.php?act=getCommentBox2",
	  	type:	'POST',
	  	cache: 	false,
	  	data:	'commentID='+CommentID+'&videoID='+artID,
	  	success: function(resp){
	  			jQuery('#quoted_comment_'+CommentID).hide();
	  			jQuery('#quoted_comment_'+CommentID).html(resp);
	  			jQuery('.id-'+CommentID).hide();
	  			jQuery('#quoted_comment_'+CommentID).show('slow');
	  		}
	});
}

// for enter form submit with action
function submitenter(myfield,e,act){
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
	   if(act) jQuery('#act').val(act);
	   myfield.form.submit();
	   return false;
   }
   else return true;
}

function makeVoting(){
	jQuery('.star-rating a').click(function(){
		if(jQuery('input:radio.star').attr('disabled')==false){
			var value = jQuery(this).attr('title');
			var action = jQuery("#rateURL").val()+'&score='+value;
		
			jQuery.ajax({
				type: 'POST',
				url: action,
				cache: false,
				data: "score=" + value,
				success: function(msg) {
					jQuery(':radio.star').rating('readOnly',true);
					jQuery(':radio.star').rating('disable');
				}
			});
		}
	 });	
}
