var page = 0;

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function checkCookie(name)
{
	var str=getCookie(name);

	if ( str != null && str != "" )
	{
		return true;
		}
	else
	{
		return false;
	}
}

function randomString(length)
{
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

function checkLogin(username,password)
{
	$("#status-message").html('<img src="' + http_site_url + 'public/images/search.gif" />');

	var cap_key = $("#vk-cap").val();

	$.post(http_site_url + '?q=login', { login: username, password: password, captcha_sid: getCookie('cap_sid'), captcha_key: cap_key }, function(data)
	{

		setCookie('cap_sid',data['cap_sid']);

		if ( data[ 'status' ] == 'captcha' )
		{

			$("#status-message").html('');
			$("#dialog-body").html("<table width='100%' cellpadding='4' cellspacing='3'>"
			+ "<tr><td><img src='" + data['captcha'] + "'></td></tr>"
			+ "<tr><td><input type='text' id='vk-cap' style='padding: 8px; font-size: 11px;' class='ui-widget-content ui-corner-all' size='40' /></td></tr>"
			+ "</table>");

		}
		else if ( data[ 'sid' ] == 0 )
		{
            if ( data['fc'] != '' )
			{
				$("#dialog-body").html('');
			}
			$("#status-message").show().html('<font color="red">Ошибка авторизации!</font>');
			return false;

		}
		else
		{
			is_logged = 1;
			$("#dialog").dialog('close');
			doSearch($("#search").val());
		}

	}, 'json');

}

var search_text = '';

function doSearch(keyword, page_i)
{

		if ( is_logged == 0 )
		{

			$('body').remove('#dialog').append("<div id='dialog' title='Войти' style='display:none'>"
			+ "<div id='status-message' style='padding: 7px; font-weight: bold;'></div><div id='dialog-body'>"
            + "<table width='100%' cellpadding='4' cellspacing='3'>"
			+ "<tr><td><b>Логин:</b></td></tr>"
			+ "<tr><td><input type='text' id='vk-login' style='padding: 8px; font-size: 11px;' class='ui-widget-content ui-corner-all' size='40' /></td></tr>"
			+ "<tr><td><b>Пароль:</b></td></tr>"
			+ "<tr><td><input type='password' id='vk-password' style='padding: 8px; font-size: 11px;' class='ui-widget-content ui-corner-all' size='40' /></td></tr>"
            //+ '<tr><td><button type="button" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false"><span class="ui-button-text">Delete all items</span></button></td></tr>'
			+ "</table>"
			+ "</div></div>");

            $( "#dialog" ).dialog({
				height: 300,
				width: 400,
				modal: true,
				open: function() {
                	$("#vk-login").focus();
				},
				create: function() {

                $("#vk-login, #vk-password").keypress(function(event) {

   					if ( event.which == '13' ) {

                    	checkLogin($("#vk-login").val(),$("#vk-password").val());

					}
				});

				},
                buttons: [
    			{
        			text: "Войти",
        			click: function() {

						checkLogin($("#vk-login").val(),$("#vk-password").val());

					}
    			},
				{
					text: "Отмена",
                    click: function() { $(this).dialog("destroy"); }
				}
				],
			});

		}
		else
		{

		var footer = $('footer');
		var opts = {
			offset: '100%'
		};

		if ( page_i == 0 ) page = 0;

		$.ajax({
            dataType: "json",
			beforeSend: function() { jLoading('Загрузка...', { autoHide: false, VerticalPosition: 'loading', HorizontalPosition: 'center', OpacityOverlay: 0.5 }); },
	        type: "POST",
			cache: false,
			url: http_site_url + '?q=search',
			success: function(data)
			{

				$("#jLoading").remove();
				$("#jOverlay").remove();

				var res = data.content;

				if ( res == 'ip_deny' )
				{
                	jError('Сервис работает только для пользователей из России!', { VerticalPosition: 'center', HorizontalPosition: 'center', TimeShown: 3000, OpacityOverlay: 0.5 });
				}
                else if ( res == 'not_logged' )
				{

					jError('Авторизуйтесь!', { VerticalPosition: 'center', HorizontalPosition: 'center', TimeShown: 3000, OpacityOverlay: 0.5 });

				}
				else
				{

				if ( data.found == '0' && document.getElementById ( 'no-results' ) )
				{

				}
				else
				{

				var e_id = randomString(10);
				res = res.replace('[id]', e_id);
				footer.waypoint('remove');

				if ( page == 1 ) {
                $("#search-result").html(res);
				} else
				$("#search-result").append(res);

				$('body').append(footer);
				footer.waypoint(opts);
                search_text = keyword;

				}

				}
			},
			data: { keyword: keyword, page: page_i },
	        error: function(data)
			{
				$("#jLoading").remove();
				$("#jOverlay").remove();
				//data.responseText
				jError('Произошла ошибка!', { clickOverlay: true, autoHide: false, HorizontalPosition: 'center', VerticalPosition: 'center', TimeShown: 5000, });
			},
		});

        page++;

		}

}

function play(id,url)
{
	uppodStopAll();

    $('.player-ctrl').each(function(index) {
    	if ( $(this).attr('id') != "player-" + id + "-ctrl" ) $(this).attr('src','/public/images/play.gif');//alert(index + ': ' + $(this).text());
  	});

	$('.player-p').each(function(index) {
		$(this).html('<div id="player-' + $(this).attr('pid') + '"></div>');
    });

    var src = $("#player-" + id + "-ctrl").attr('src');

	if ( src == '/public/images/play.gif' )
	{
		uppodErrorReport("player-"+id);
		$("#player-" + id + "-ctrl").attr('src','/public/images/stop.gif');
		var flashvars = {"m":"audio",st:"/public/js/style40020black.txt","file":url,"uid":"player-"+id};
		var params = {id:"player-"+id, bgcolor:"#cfcfcf", allowFullScreen:"true", allowScriptAccess:"always"};
		new swfobject.embedSWF("/public/swf/uppod.swf", "player-"+id, "400", "22", "9.0.115", false, flashvars, params);
    }
	else
	{
		$("#player-" + id + "-ctrl").attr('src','/public/images/play.gif');
    	$("#player-" + id).html('');
	}
}

$(document).ready(function(){

	var footer = $('footer');
	var opts = {
		offset: '100%'
	};

	footer.waypoint(function(event, direction) {
		if ( page >= 1 ) {
			doSearch($("#search").val(),page);
	   	}
	}, opts);

	$("#search").keypress(function(event) {

   		if ( event.which == '13' ) {

			doSearch($("#search").val(),0);

		}

	});

	$("#doSearch").click(function(){

		doSearch($("#search").val(),0);

	});

});
