function trySearch()
{
	if ($('#searchText').val().length < 2)
	{
		alert('поле должно содержать по крайней мере 3 символа');
	}else
	{
		$('#searchFrom').submit();
	}
}




function showOrHideAllDropDowns(newState) {
  var elements = document.documentElement.getElementsByTagName('select');
  for (var i=0; i<elements.length; i++) {
    elements[i].style.visibility = newState;
  }
}

function win_close()
{
    document.getElementById('blocker').style.display='none';
    document.getElementById('win').style.display='none';
    document.getElementById('comment').style.display='none';
    document.getElementById('hiw').style.display='none';
    document.getElementById('code').style.display='none';
    document.getElementById('emailDiv').style.display='none';
    document.getElementById('emailAnswer').style.display='none';
}

function win(id,state)
{
    if (state == 1)
        win_close();

  if (id=='win'&&state==1) {
  document.getElementById('blocker').style.display='block';
  document.getElementById('win').style.display='block';
  showOrHideAllDropDowns('hidden');
  return 0;
  }
  if (id=='win'&&state==0) {
  document.getElementById('blocker').style.display='none';
  document.getElementById('win').style.display='none';
  showOrHideAllDropDowns('visible');
  return 0;
  }
  if (id=='comment'&&state==1) {
  document.getElementById('comment').style.display='block';
  showOrHideAllDropDowns('hidden');
  return 0;
  }
  if (id=='comment'&&state==0) {
  document.getElementById('comment').style.display='none';
  showOrHideAllDropDowns('visible');
  return 0;
  }
  if (id=='hiw'&&state==1) {
  document.getElementById('hiw').style.display='block';
  showOrHideAllDropDowns('hidden');
  return 0;
  }
  if (id=='hiw'&&state==0) {
  document.getElementById('hiw').style.display='none';
  showOrHideAllDropDowns('visible');
  return 0;
  }
  if (id=='code'&&state==1) {
  document.getElementById('code').style.display='block';
  showOrHideAllDropDowns('hidden');
  return 0;
  }
  if (id=='code'&&state==0) {
  document.getElementById('code').style.display='none';
  showOrHideAllDropDowns('visible');
  return 0;
  }
  if (id=='emailDiv'&&state==1)
  {
    $('#nameEmail' ).val('');
    $('#emailEmail').val('');
    $('#textEmail' ).text('');
    $('#captcha').val('');
    win_email_chg('')
    document.getElementById('emailDiv').style.display='block';
    showOrHideAllDropDowns('hidden');
    return 0;
  }
  if (id=='emailDiv'&&state==0) {
  document.getElementById('emailDiv').style.display='none';
  showOrHideAllDropDowns('visible');
  return 0;
  }
  if (id=='emailAnswer'&&state==1) {
  document.getElementById('emailAnswer').style.display='block';
  showOrHideAllDropDowns('hidden');
  return 0;
  }
  if (id=='emailAnswer'&&state==0) {
  document.getElementById('emailAnswer').style.display='none';
  showOrHideAllDropDowns('visible');
  return 0;
  }

}
showBook = 0;
function bookmarkall()
{
    if ($('#bookmark').css('display') == 'block')
    {
        $('#bookmark').hide();
        return;
    }
    else
    {
        if (showBook == 1)
            $('#bookmark').show();
    }
    this.selection=function() {
        var sel;
        if (window.getSelection)
            sel=window.getSelection();
        else if (document.selection)
            sel=document.selection.createRange();
        else
            sel='';
        if (sel.text)
            sel=sel.text;
        return encodeURIComponent(sel);
    }
    var title=encodeURIComponent(document.title);
    var url=encodeURIComponent(location.href);
    var titles=new Array(
             '&#1041;&#1086;&#1073;&#1088;&#1044;&#1086;&#1073;&#1088;',
             'Memori',
             '&#1052;&#1080;&#1089;&#1090;&#1077;&#1088; &#1042;&#1086;&#1085;&#1075;',
             'del.icio.us',
             '&#1071;&#1085;&#1076;&#1077;&#1082;&#1089;.&#1047;&#1072;&#1082;&#1083;&#1072;&#1076;&#1082;&#1080;',
             '&#1047;&#1072;&#1082;&#1083;&#1072;&#1076;&#1082;&#1080; Google',
             '&#1058;&#1077;&#1082;&#1089;&#1090; 2.0',
             '&#1055;&#1080;&#1089;a&#1083;&#1080;',
             'News2',
             '&#1057;&#1052;&#1048; 2',
             'AddScoop',
             '&#1052;&#1086;&#1105;&#1052;&#1077;&#1089;&#1090;&#1086;',
             'RuSpace',
             '&#1057;&#1090;&#1086; &#1047;&#1072;&#1082;&#1083;&#1072;&#1076;&#1086;&#1082;',
             'RUmarkz',
             '&#1042;&#1072;&#1072;&#1091;!'
            );
            var html = new String('');
    for (i=0;i<17;i++)
    {
        switch(i+1)
        {
            case  1: href = 'http://bobrdobr.ru/addext.html?url='+url+'&title='+title;break;
            case  2: href = 'http://memori.ru/link/?sm=1&u_data[url]='+url+'&u_data[name]='+title;break;
            case  3: href = 'http://www.mister-wong.ru/index.php?action=addurl&bm_url='+url+'&bm_description='+title;break;
            case  4: href = 'http://del.icio.us/post?v=4&noui&jump=close&url='+url+'&title='+title;break;
            case  5: href = 'http://zakladki.yandex.ru/userarea/links/addfromfav.asp?bAddLink_x=1&lurl='+url+'&lname='+title;break;
            case  6: href = 'http://www.google.com/bookmarks/mark?op=add&bkmk='+url+'&title='+title;break;
            case  7: href = 'http://text20.ru/add/?source='+url+'&title='+title+'&text='+this.selection();break;
            case  8: href = 'http://pisali.ru/load_article/';break;
            case  9: href = 'http://news2.ru/add_story.php?url='+url;break;
            case 10: href = 'http://smi2.ru/add/';break;
            case 11: href = 'http://myscoop.ru/add/?URL='+url+'&title='+title;break;
            case 12: href = 'http://moemesto.ru/post.php?url='+url+'&title='+title;break;
            case 13: href = 'http://www.ruspace.ru/index.php?link=bookmark&action=bookmarkNew&bm=1&url='+url+'&title='+title;break;
            case 14: href = 'http://www.100zakladok.ru/save/?bmurl='+url+'&bmtitle='+title;break;
            case 15: href = 'http://rumarkz.ru/bookmarks/?action=add&popup=1&address='+url+'&title='+title;break;
            case 16: href = 'http://www.vaau.ru/submit/?action=step2&url='+url; break;
            default:
                continue;
        }
        html+='<a href="'+href+'"><img src="/images/blank.gif" width="16" height="16" alt=" #" title="'+titles[i]+'" style="border:0;padding:0;margin:0 4px 0 0;background:url(/images/icons.gif) -'+(i*16)+'px"/></a>';
    }
    html+='<a href="javascript:void(0);" onclick="return bookmark(this);" title="Добавить в закладки браузера"><img src="/images/ie.gif" width="16" height="16"/></a>';
    html+='</div>';
    $('#bookmark').attr('innerHTML', html).show();
    showBook = 1;
}

function getBrowserInfo() {
    var t,v = undefined;
    if (window.opera) t = 'Opera';
    else if (document.all) {
        t = 'IE';
        var nv = navigator.appVersion;
        var s = nv.indexOf('MSIE')+5;
        v = nv.substring(s,s+1);
    }
    else if (navigator.appName) t = 'Netscape';
    return {type:t,version:v};
}

function bookmark(a){
    var url = window.document.location;
    var title = window.document.title;
    var b = getBrowserInfo();
    if (b.type == 'IE' && 7 > b.version && b.version >= 4) window.external.AddFavorite(url,title);
    else if (b.type == 'Opera') {
        a.href = url;
        a.rel = "sidebar";
        a.title = url+','+title;
        return true;
    }
    else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
    else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
    return false;
}

function showWin(theURL)
{
    var winName = '';
    var width = 600;
	var height = 700;
    var features = 'width=' + width + ', height=' + height + ', titlebar=no, resizable=no, status=no, scrollbars=yes';

	SendWin=window.open(theURL,winName,features);
	SendWin.focus();
	return false;
}

function OpenFile(url,width,height)
{
	var Left = (screen.width - width) / 2 - 5;
	var Top = (screen.height - height) / 2 - 29;
	var Scroll = typeof(arguments[3])=='undefined'?'no':arguments[3];
	shown=window.open(url,"","top="+Top+",left="+Left+",width="+width+",height="+height+",scrollbars="+Scroll+",status=no,resizable=yes,high");
	return false;
}

function showPlay(theGame)
{
    mark_download('', theGame);
    var winName = '';
    var width = 1020;
	var height = 600;
    var features = 'width=' + width + ', height=' + height + ', titlebar=no, resizable=no, status=no, scrollbars=yes';

    theURL = '/popup/play/?id=' + theGame;

	SendWin=window.open(theURL,winName,features);
	SendWin.focus();

	return false;
}

function voting_send( vote )
{
    $.post('/ajax/rating/vote/', { game_id: $('#game_id').val(), vote: vote, rand: Math.random() },
        function(data)
        {
            data = data.split('|');

            if (data[0] == 'success')
            {
                result = '';
                result+= '<ul class="rate" title="Рейтинг: '+ data[2] +'">';
                result+= (data[1] == 1) ? '<li class="one cur">1</li>'  : '<li class="one">1</li>'  ;
                result+= (data[1] == 2) ? '<li class="two cur">2</li>'  : '<li class="two">2</li>'  ;
                result+= (data[1] == 3) ? '<li class="three cur">3</li>': '<li class="three">3</li>';
                result+= (data[1] == 4) ? '<li class="four cur">4</li>' : '<li class="four">4</li>' ;
                result+= (data[1] == 5) ? '<li class="five cur">5</li>' : '<li class="five">5</li>' ;
                result+= '</ul>';
                result+= '<p>ваш голос учтен</p>';

                $('#gameRate').html( result );
            }
        }
    );
}


function vg_voting_send( vote )
{
    $.post('/voice/vote/', {vote: vote, rand: Math.random() },
        function(data)
        {
            data = data.split('|');

            if (data[0] == 'success')
            {
                result = '';
                result+= '<ul class="rate" title="Рейтинг: '+ data[2] +'">';
                result+= (data[1] == 1) ? '<li class="one cur">1</li>'  : '<li class="one">1</li>'  ;
                result+= (data[1] == 2) ? '<li class="two cur">2</li>'  : '<li class="two">2</li>'  ;
                result+= (data[1] == 3) ? '<li class="three cur">3</li>': '<li class="three">3</li>';
                result+= (data[1] == 4) ? '<li class="four cur">4</li>' : '<li class="four">4</li>' ;
                result+= (data[1] == 5) ? '<li class="five cur">5</li>' : '<li class="five">5</li>' ;
                result+= '</ul>';
                result+= '<p>ваш голос учтен</p>';

                $('#gameRate').html( result );
            }
        }
    );
}


function getVSMSCode()
{
    var name = $('#ph_name').attr('value');
    var ph_to =$('#ph_to').attr('value');

        $.post('/voice/order/?stamp=' + Math.random() , { ph_to: ph_to, name: name},
        function(data)
        {
            var data_decoded = $.parseJSON(data);
            if(!data_decoded['error'])
            {
                $('#voice_code').html(data_decoded['smscode']);
				$('#voice_code2').html(data_decoded['smscode']);
				$('#voice_user').html($('#ph_name').attr('value'));
                $('#rival_number').html('+' + ph_to);
				$('#step1').hide(); $('#step2').show();
                //$('#blocker').show();$('#voice_win').show();
                //$('#ph_name').attr('value','');
                //$('#ph_to').attr('value','7');
            }
            else
            {
                if(data_decoded['error'] == 2)
                {
                    alert('Проверьте корректность введенного телефонного номера');
                    return false;
                }
                else if(data_decoded['error'] == 3)
                {
                    alert('Проверьте корректность введенного имени');
                    return false;
                }
                else
                {
                    alert('Произошла ошибка. Попробуйте воспользоваться сервисом немного позднее');
                }
            }
        }
    )
}


function loadSWF(id, url)
{
    swfobject.embedSWF('/swf/player.swf', id, "40", "48", "8.0.0", "", {BaseURL:url, t:'pt'}, { wmode: "opaque" ,play:'true'});
}

function model_get( vendor , gameId)
{
    if ( vendor == 0 || gameId == 0)
    {
        $('#model').html( '<option value="0">-</option>' );
        $('#model').attr('disabled', 'disabled');
        return;
    }
    $.post('/ajax/phone/model/', { vendor: vendor, gameId: gameId },
        function(data)
        {
            data = data.split('|');

            if (data[0] == 'success')
            {
                $('#model').html( data[1] );
            }
        }
    );
    $('#model').attr('disabled', '');
}

/**
 * Обработчик получения сервисного кода
 */
function code_get(g_id)
{
    var opId = loadSelectVal('operator');
    var phId = loadSelectVal('model');

    $.post('/ajax/buy/getcode/', { op_id: opId, ph_id: phId, g_id: g_id },
        function(data)
        {
           var data_decoded = $.parseJSON(data);

           if(!data_decoded['error'])
           {
               var code     = data_decoded['code'];
               var isnn     = data_decoded['isnn'];
               var inclnds  = data_decoded['inclnds'];
               var currency = data_decoded['currency'];

               /**
                * Если очень хочется - то дополнительно можно тут в окне отображать цену
                * и прочие параметры игры
                */
               var price    = data_decoded['price'];
               var prefix   = data_decoded['prefix'];
               var name     = data_decoded['name'];

               $('#mobile_code').html(prefix + code);
               $('#isnn').html('На номер ' + isnn);
               $('#code_name').html(name);

               $('#win').show();
			   $('#blocker').show();
           }else
           {
               if(data_decoded['error']==1)
               {
                   alert('Укажите вашего оператора!');
               }
               else
               {
                   alert('Проверьте, все ли поля заполнены');
               }
           }
        }
    )
}

function mark_download( url, game_id)
{
    if ( ! game_id)
    {
        game_id = $('#game_id').val();
    }

    $.post('/ajax/game/download/', { game_id: game_id },
        function(data)
        {
            data = data.split('|');

            if (data[0] == 'success' && url != '')
            {
                document.location = url;
            }
            else
            {
                return false;
            }
        }
    );
}


function mark_download_megapack(url, rubric)
{
    $.post('/ajax/megapack/download/', { dl: 1, rubric: rubric},
        function(data)
        {
            if (data[0] == 'success' && url != '')
            {
                document.location = url;
            }
            else
            {
                return false;
            }
        }
    );
}

function win_comment_show()
{
    $('#capimg').attr('src', '/captcha.php?' + Math.random());
    win('comment', 1);
}


function win_comment_close()
{
    $('#name'   ).val('');
    $('#email'  ).val('');
    $('#text'   ).val('');
    $('#captcha').val('');
    win('comment', 0);
}

/**
 * Функция реализует интерфейс стандартного окна добавления комментов
 */
function win_comment_send()
{
    $('#errName' ).html('');
    $('#errEmail').html('');
    $('#errText' ).html('');
    $('#errCaptcha').html('');

    $.post('/ajax/comment/add/', { name:    $('#name'   ).val(),
                                   email:   $('#email'  ).val(),
                                   text:    $('#text'   ).val(),
                                   captcha: $('#captcha').val(),
                                   game_id: $('#game_id').val()
                                 },
        function(data)
        {
            $('#capimg').attr('src', '/captcha.php?' + Math.random());

            if (data.substr(0, 5) == 'error')
            {
                result = data.split('|');

                if (result[1] == 'name')
                {
                    $('#errName').html( result[2] );
                }
                else if (result[1] == 'email')
                {
                    $('#errEmail').html( result[2] );
                }
                else if (result[1] == 'text')
                {
                    $('#errText').html( result[2] );
                }
                else if (result[1] == 'captcha')
                {
                    $('#errCaptcha').html( result[2] );
                }

                $('#captcha').val('');
            }
            else if (data.substr(0, 7) == 'success')
            {
                document.location.href = location.pathname + '?comments=' + data.substr(8);
            }
        }
    );
}

/**
 * Функция реализует интерфейс стандартного окна добавления комментов
 * для голосовой игрушки
 */
function vg_win_comment_send()
{
    $('#errName' ).html('');
    $('#errEmail').html('');
    $('#errText' ).html('');
    $('#errCaptcha').html('');

    $.post('/voice/comment/add/', { name:    $('#name'   ).val(),
                                    email:   $('#email'  ).val(),
                                    text:    $('#text'   ).val(),
                                    captcha: $('#captcha').val()
                                 },
        function(data)
        {
            $('#capimg').attr('src', '/captcha.php?' + Math.random());

            if (data.substr(0, 5) == 'error')
            {
                result = data.split('|');

                if (result[1] == 'name')
                {
                    $('#errName').html( result[2] );
                }
                else if (result[1] == 'email')
                {
                    $('#errEmail').html( result[2] );
                }
                else if (result[1] == 'text')
                {
                    $('#errText').html( result[2] );
                }
                else if (result[1] == 'captcha')
                {
                    $('#errCaptcha').html( result[2] );
                }

                $('#captcha').val('');
            }
            else if (data.substr(0, 7) == 'success')
            {
                document.location.href = location.pathname + '?comments=' + data.substr(8);
            }
        }
    );
}

function loadSelectVal(id){
	var p = document.getElementById(id);
	var v =p.options[p.selectedIndex].value;
	return v;
}