//
// Here we go again...
//

var to;
var timeout = 3000;
var aspeed = 1000;
var positions = 4;
var current = 0, index = 0, padding = 11;
var active = false;

var expand_comment_form = 'comment_form';

function news_switcher(pos, clicked)
{
	if(!active)
	{
		active = true;
		
		if(clicked)
		{
			clearTimeout(to);
		}
		if(pos > 4 || pos < 0)
		{
			pos = 1;
		}
		var move_to = 0;
		if(pos != 0)
		{
			for(var i = 1; i <= pos; i++)
			{
				move_to += $('#topnews-news li:nth-child('+ i + ')').height();
				move_to += padding;
			}
		}
		else
		{
			move_to = 0;
		}
		$('#topnews-news li').removeClass('active');
		$('#topnews-news li:nth-child('+(pos+1)+')').addClass('active');
		var img_name = $('#topnews-news li.active dd a').attr('rel');
		$('#topnews-image').animate({
			opacity: 0
		}, aspeed/2, function() {
			$('#topnews-image img').attr('src', img_name);
			$('#topnews-image').animate({
				opacity: 1
			}, aspeed/2);
		});
		$('#topnews .marker').animate({
			top: (move_to + 11)
		}, aspeed, function() {
			pos++;
			if(pos > 3)
			{
				pos = 0;
			}
			if(clicked)
			{
				active = false;
				to = setTimeout('news_switcher('+pos+'), false', timeout + aspeed);
				return;
			}
			
			active = false;
			to = setTimeout('news_switcher('+pos+'), false', timeout + aspeed);
		});
	}
} // End news-switcher()


//
// Cookies management:
//

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

// End cookies

// ----------------
// Facebook share:
// ----------------

function fbs_click() {
	u = location.href;
	t = document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

// ----------------
// END fb share
// ----------------

//
// Dropdown menus:
//
var ddto;
var ddid = '';
var cddid = '';

function show_menu(el)
{
	cddid = $(el).attr('rel');
	cancel_menu_timeout();
	if(ddid != cddid && ddid != '')
	{
		hide_menu();
	}
	ddid = cddid;
	$('#'+ddid).fadeIn('fast');
	$('#parent-'+ddid).addClass('hover');
}

function cancel_menu_timeout()
{
	if(ddto)
	{
		window.clearTimeout(ddto);
		ddto = null;
	}
}

function hide_menu()
{
	$('#'+ddid).fadeOut('fast');
	$('#parent-'+ddid).removeClass('hover');
}

function close_menu()
{
	ddto = window.setTimeout('hide_menu("'+ ddid +'")', 100);
}

// 
// END dropdown menus.
// ...................

//
// "Best price" picker:
//

var selected_products = [];

function ps_get_id(id)
{
	var tmp = id.split('-');
	return tmp[1];
}

function ps_get_array_id(id)
{
	for(var i = 0; i < selected_products.length; i++)
	{
		if(id == selected_products[i])
		{
			return i;
		}
	}
}

function ps_in_array(id)
{
	for(var i = 0; i < selected_products.length; i++)
	{	
		if(id == selected_products[i])
		{
			return true;
		}
	}
	return false;
}

function ps_remove_product(id)
{
	if(ps_in_array(id))
	{
		var rmv = selected_products.splice(ps_get_array_id(id), 1);
	}
	else
	{
		return;
	}
}

function ps_add_product(id)
{
	if(!ps_in_array(id))
	{
		selected_products[selected_products.length] = id;
	}
	else
	{
		ps_remove_product(id);
	}
	try
	{
		document.getElementById('categories').value = selected_products.toString();
	} catch(e) { alert('Имаше грешка при маркирането на продукт!'+"\n\t"+e.description); }
}


//
// Temp:
//

var tmp_msg = '';
var tmp_msgs = ["Потребител", "Парола", "Намери най-добрите оферти"];

function is_valid_predefined_input(msg)
{
	for(var i = 0; i < tmp_msgs.length; i++)
	{
		if(msg == tmp_msgs[i])
		{
			return true;
		}
	}
	return false;
}

function clear_input(input)
{
	tmp_msg = input.value;
	if(is_valid_predefined_input(tmp_msg))
	{
		input.value = '';
	}
	input.onblur = function() {
		if(input.value == '')
		{
			input.value = tmp_msg;
		}
	}
}

function likeThisPage(loc) {
myVar='<iframe src="http://www.facebook.com/plugins/like.php?href='+document.location+';layout=standard&amp;show_faces=true&amp;width=300&amp;action=like&amp;colorscheme=light&amp;height=60" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:300px; height:60px;" allowTransparency="true"> </iframe>';

/*===== DEBUG =====
	  return myVar;
	  =============*/
	  
$(loc).html(myVar);
}

$(document).ready(function () {
    
    var url_link="";
    var align="";
    var br = 1;
    $('#article-text img.zoom-img').each(function(index) {
            
			var width = $(this).width();
            var url_link = $(this).attr("src");
            var align = $(this).attr("align");
            if(align=="left") classDiv = "alignleft";
            else if(align=="right") classDiv = "alignright";
            else if(align!="") classDiv = "aligncenter";
            else classDiv="";
			
            var rel = $(this).attr("rel");
            if(url_link != "")
            {
                tmp = url_link.split("/");
                file = tmp[3];                
                newlink = '/uploads/th640/'+file+'';
                
            }
            $(this).wrapAll('<span class=\"article-image zoom '+classDiv+'\" id="file_'+br+'" ></span>');
            $("#file_"+br+"").append('<a class="lightbox" href="'+newlink+'"><span>увеличете изображението</span></a>');
			br++;
    });

	
	if(current == 0)
	{
		to = setTimeout('news_switcher(1, false)', timeout);
	}
	
	// --------------------
	// Topnews teaser:
	// --------------------
	$('#topnews-news li').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	$('#topnews-news li').click(function() {	
		var index = $('#topnews-news li').index($(this));
		news_switcher(index, true);
	});
	// 
	// END Topnews teaser
	// //////////////////
	
	// ----------------------
	// Best price selector:
	// ----------------------
	$('#bestprice ul.selector li').click(function() {
		var pid = ps_get_id($(this).attr('id'));
		$(this).toggleClass('clicked');
		if(0 === ps_add_product(pid))
		{
			alert('already exists!');
		}
		else
		{
			$('#sidebar #items').html(selected_products.toString());
		}
	});
	
	// ---------------------------
	// Best price selector hover:
	// ---------------------------
	$('#bestprice ul.selector li').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	);
	
	// -------------------------
	// Best price options:
	// -------------------------
	$('#bestprice .options li').click(function() {
		$(this).toggleClass('clicked');
		
		var id = ps_get_id($(this).attr('id'));
		
		if($(this).hasClass('clicked'))
		{
			$('#hopt-'+id).val('1');
		}
		else
		{
			$('#hopt-'+id).val('0');
		}
	});
	
	
	// ------------------------
	// Box content switcher:
	// ------------------------
	
	$('.switchable h2 a').click(function() {
		$('.switchable h2 a').removeClass('sel');
		$(this).addClass('sel');
		
		$section = $(this).attr('rel');
		
		$('#sidebar .switchable .content').addClass('hide');
		$('#sidebar .switchable #' + $section).removeClass('hide');
		
		return false;
	});
	
	// -----------------------
	// Comments-form expand:
	// -----------------------
	try {
		if(readCookie(expand_comment_form) == null)
		{
			$('#comment-form').hide();
		}
		else
		{
			$('#comment-form').show();
		}
	} catch(e) {  }
	$('p.addcomment a').click(function() {
		$('#comment-form').slideToggle('slow');
		if(readCookie(expand_comment_form) == null)
		{
			createCookie(expand_comment_form, '1', 7);
		}
		else
		{
			createCookie(expand_comment_form, '0', -1);
		}
		return false;
	});
	
	
	
	// Login animation:
	$('#account #login').click(function() {
		$('#account-inner').fadeOut('fast', function() {
			
			$('#account-inner').html(
				'<form id="quick-login-form" action="/forum/login.php?login=1" method="post">' +
				'	<div><input id="quick-login-user" type="text" class="text" name="username" value="Потребител" onfocus="clear_input(this);" /></div>' +
				'	<div><input type="password" class="text" name="password" value="Парола" onfocus="clear_input(this);"/></div>' +
				'	<p>' +
				'		<input class="submit" type="image" src="/html/gfx/form_login.gif" value="Вход" name="doLogin" />' +
				'		<a class="reset-pass" title="Забравена парола" href="/club/newpass.html"><img src="/html/gfx/icon_resetpass.gif" alt="Забравена парола" /></a>' +
				'	</p>' +
				'</form>'
			);
			
			// Fix for IEs
			$('#quick-login-form input').keydown(function(e){
				if (e.keyCode == 13) {
					$(this).parents('form').submit();
					return false;
				}
			});
			
			$('#account-inner').fadeIn('fast', function() {
				$('#quick-login-user').fadeOut(200, function() {
					$('#quick-login-user').show().focus();
				});
			});
		});
		
		// one's for certain
		return false;
	});
	
	//Send friend
	$('.close-friend').click(function() {$('#sendfriend-form').slideToggle('slow');})
	$('.send a').click(function() {
		$('#sendfriend-form').slideToggle('slow');
		//location.href="#sendtofriend";
		
		return false;
	});
	
	$("#sendtofriend").submit(function()
	{
       // var page=strstr(location.href,"/p3");
        var page=location.href;
        if($("#yourname").val()&&$("#recname").val()&&$("#yourmail").val()&&$("#recmail").val()&&validate_email($("#yourmail").val())&&validate_email($("#recmail").val())&&page)    
         {
            $.post("/scripts/_script_sendarticle.php",{"name1":$("#yourname").val(),"name2":$("#recname").val(),"email1":$("#yourmail").val(),"email2":$("#recmail").val(),"page":page},function(data) { 
                    var res=data.split("|");
                    if(res[1])
                           {
                            alert(res[0]);
                            $("#yourname").val('');
                            $("#recname").val('');
                            $("#yourmail").val('');
                            $("#recmail").val('');
                            $('#sendfriend-form').slideToggle('slow');
                            }
                    else alert(res[0]);        
                    });
        }
       else alert("Моля попълнете полетата"); 
        return false;
    });
	// end send friend
	
	
	// ============
	// Fancybox
	// ============
	
	$("a.lightbox").fancybox({
		'speedIn'		:	600,
		'speedOut'		:	200,
		'overlayShow'	:	false
	});
	
	// ==============
	// END Fancybox
	// ==============
	
	// -----------------
	// Social Sharing:
	// -----------------
	
	// Svejo:
	/*
	$('#article li.fbook a').click(function() {
		
		//window.open('http://www.facebook.com/share.php?u=&lt;url&gt;', '_blank', 'width=640,height=480');
		//return false;
		
	});*/
	
	
	// ------------------
	// END Social Sharing
	// ------------------
	
	$("#category").change(function(){ 
	var id=$(this).val();	
	$("#Father").removeOption(/./);
	$("#Father").ajaxAddOption("/scripts/script_fathers.php",{"id":id},false);
});

	
});

$(function() {
	//scrollpane parts
	var scrollPane = $('.scroll-pane');
	var scrollContent = $('.scroll-content');
	
	//build slider
	var scrollbar = $(".scroll-bar").slider({
		slide:function(e, ui){
			if( scrollContent.width() > scrollPane.width() ){ scrollContent.css('margin-left', Math.round( ui.value / 100 * ( scrollPane.width() - scrollContent.width() )) + 'px'); }
			else { scrollContent.css('margin-left', 0); }
		}
	});
	
	$('.ui-slider-handle').removeClass('ui-corner-all');
	
	//append icon to handle
	var handleHelper = scrollbar.find('.ui-slider-handle')
	.mousedown(function(){
		scrollbar.width( handleHelper.width() );
	})
	.mouseup(function(){
		scrollbar.width( '100%' );
	})
	.append('<span class="ui-leftarrow"></span><span class="ui-rightarrow"></span>')
	.wrap('<div class="ui-handle-helper-parent"></div>').parent();
	
	//change overflow to hidden now that slider handles the scrolling
	scrollPane.css('overflow','hidden');
	
	//size scrollbar and handle proportionally to scroll distance
	function sizeScrollbar(){
		var remainder = scrollContent.width() - scrollPane.width();
		var proportion = remainder / scrollContent.width();
		var handleSize = scrollPane.width() - (proportion * scrollPane.width());
		scrollbar.find('.ui-slider-handle').css({
			width: handleSize,
			'margin-left': -handleSize/2
		});
		handleHelper.width('').width( scrollbar.width() - handleSize);
	}
	
	//reset slider value based on scroll content position
	function resetValue(){
		var remainder = scrollPane.width() - scrollContent.width();
		var leftVal = scrollContent.css('margin-left') == 'auto' ? 0 : parseInt(scrollContent.css('margin-left'));
		var percentage = Math.round(leftVal / remainder * 100);
		scrollbar.slider("value", percentage);
	}
	//if the slider is 100% and window gets larger, reveal content
	function reflowContent(){
			var showing = scrollContent.width() + parseInt( scrollContent.css('margin-left') );
			var gap = scrollPane.width() - showing;
			if(gap > 0){
				scrollContent.css('margin-left', parseInt( scrollContent.css('margin-left') ) + gap);
			}
	}
	
	//change handle position on window resize
	$(window)
	.resize(function(){
			resetValue();
			sizeScrollbar();
			reflowContent();
	});
	//init scrollbar size
	setTimeout(sizeScrollbar,10);//safari wants a timeout
});

 function validate_email(value) {
			// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
			if( /^((([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.test(value)) return 1;
			else return 0;
		}
function gamesvote(vi)
{
   
    //var vi=$("input[name=answer]:checked").val();
    //var vi=$('input:radio[name=answer]:checked').val();
    var gid=$("#gid").val();
    var qid=$("#qid").val();
    var num=$("#num").val();
    var all=$("#allq").val();
    
    if(vi) 
    {$.post("/games/_scripts_vote.php",{"vote":vi,"gid":gid,"qid":qid,"offset":num},function(data) 
	{  
        res=data.split("|");        	
		if(parseInt(res[1])>0) 
		{
           if(parseInt(num+1)>=all) location.href="/games/result/";           
           else location.href="/games/"+parseInt(num+1)+"";           
          
		}
		else alert(res[2]);
		
	});
	}
    else alert("Моля Изберете един от отговорите");
}