var CommentProto;
var visibility = new Hash();
var Store = new Hash();
var download_timer, enable_timer, video_html;

function comment(_date,_nick,_note) {
    $('AllComments').appendChild(CommentProto.cloneNode(true));
    var ocom = $('AllComments').lastChild;
    var cdate = ocom.getElementsByClassName('date')[0];
    var note = ocom.getElementsByClassName('note')[0];
    var nick = ocom.getElementsByClassName('nick')[0];
    cdate.update(_date);
    note.update(_note);
    if(nick)
        nick.update(_nick);
    ocom.show();
}

function CInit(id) {
    CommentProto = $('CommentProto');
    if(CommentProto)
	CommentProto.removeAttribute('id');
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    new Ajax.Request(
        '/comments',
	    {
    	       method: 'get',
    	       parameters: { action: 'get', file_id: id, rand: randpar },	
     	       onSuccess: function(oReq) {
		    eval('data='+oReq.responseText);
		    if(data.status == 'OK') {
			for(var i=0;i < data.comments.length;i++)
			  {
			    comment(data.comments[i].date,data.comments[i].nickname,data.comments[i].note);
			  }
		    }
               },
               onFailure: function () { }
            }
	);
}

function subscribe(name) {
    var email = prompt("Укажите Ваш email, на который Вы хотите получать информацию о похожих файлах на WebFile и в сети Интернет:","");
    if(!email)
	return;
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    new Ajax.Request(
        '/subscribe',
            {
        	 method: 'get',
        	 parameters: { email: email, name: name, rand: randpar },	
    
	         onSuccess: function(oReq) { 
		    $('subscribe_link').hide();
		 },
        	 onFailure: function () { }
            }
    );
    return;
}

function remind_pass() {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var email = prompt("Email:","");
    new Ajax.Request (
	'/user',
	{
	    method: 'get',
	    parameters: { email: email, rand: randpar },
	    
	    onSuccess: function(oReq) {
		eval('data='+oReq.responseText);
		if(data.status == 'OK')
		    alert("Пароль выслан на указанный e-mail");
		else
		    alert("Пользователь не найден.");
	    },
	    onFailure: function () { }
	}
    );
}

    var curhint,locked=false;
    var ancs=document.getElementsByTagName('a');
    for(i=0;i<ancs.length;i++)
        if(ancs[i].className=='hint')
        {
            ancs[i].onmouseover=showHint;
            ancs[i].onmousemove=showHint;
            ancs[i].onmouseout=hideHint;
            ancs[i].onclick=new Function('','return false');
        }

    function showHint()
    {
        this.hint=document.getElementById(this.id+'div');
        if(locked)return false;
        locked=true;
        curhint=this.hint;
        this.hint.style.display='';
        this.hint.style.top=this.offsetTop+this.offsetHeight+6;
        this.hint.style.left=this.offsetLeft;//+this.offsetWidth+10;
        this.hint.style.width=250;
    }

    function hideHint()
    {
        curhint.onmouseover=showHint;
        setTimeout("curhint.style.display='none';locked=false;",10*25);
    }

    function Bookmark()
    {
      var url="http://webfile.ru";
      var title=window.document.title;
      if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function"))  window.sidebar.addPanel (title, url, "");
      else if (typeof window.external == "object") window.external.AddFavorite(url, title);
      else if (window.opera && document.createElement)
	{
    	  var a = document.createElement('A');
          if(a) {
    	     a.setAttribute('rel','sidebar');
             a.setAttribute('href',url);
             a.setAttribute('title',title);
             a.click();
          }
	}
      return false;
    }
function change_email_tip_on() {
    $('ChangeEmailTip').show();
}
function change_email_tip_off() {
    $('ChangeEmailTip').hide();
}
function change_pass() {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var pass = prompt("Новый пароль:","");
    if(!pass)
        return;
    new Ajax.Request(
        '/user',
          {
             method: 'get',
             parameters: { newpass: pass, rand: randpar },

             onSuccess: function(oReq) { alert("Пароль изменен."); },
             onFailure: function () { }
          }
     );
}

function change_email() {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var email = prompt("Новый email:","");
    if(!email)
        return;
    new Ajax.Request(
        '/user',
          {
             method: 'get',
             parameters: { newemail: email, rand: randpar },

             onSuccess: function(oReq) { alert("Вам выслан код для подтверждения адреса."); },
             onFailure: function () { }
          }
     );
}

function send_fileurl(file_id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var addr = prompt("Email:","");
    new Ajax.Request(
        '/mail',
          {
             method: 'get',
             parameters: { action: 'fileurl', to: addr, id: file_id, rand: randpar },

             onSuccess: function(oReq) { },
             onFailure: function () { }
          }
     );
}

function Hide_RM_Banner() {
    //$('rich_wiw_banner').hide();
    if($('rich_wiw_banner'))
	$('rich_wiw_banner').parentNode.removeChild($('rich_wiw_banner'));
    Set_Cookie('rwiw','1');
}

function access_code_tip_on() {
    $('AccessCodeTip').show();
}
function access_code_tip_off() {
    $('AccessCodeTip').hide();
}

function add_comment(id) {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var nick = "";
    if($('nickname') && $('nickname').value)
        nick = $('nickname').value;
    var email = "";
    if($('email') && $('email').value)
        email = $('email').value;
    
    new Ajax.Request(
        '/comments',
        {
    	    method: 'get',
    	    parameters: { action: 'add', file_id: id, note: $('new_comment').value, nick: nick, email: email, rand: randpar },	
            onSuccess: function(oReq) {
		eval('data='+oReq.responseText);
		if(data.status == 'OK')
		  {
		    var now = get_date();
                    if(!nick)
                        nick = 'anonymous';
		    comment(now,nick,$('new_comment').value);
		    $('new_comment').value='';
		    $('email').value='';
		  }
		else 
		  {
		    alert('Ошибка');
		  }
            },
            onFailure: function () { alert('Ошибка'); }
        }
    );
    return false;
}

function get_date() {
    var date = new Date();
    var now;
    var date = new Date();
    var year = (date.getYear() < 2008) ? date.getYear()+1900 : date.getYear();
    var mon = (date.getMonth()+1);
    if(mon<10)
      mon='0'+mon;
    var mday = date.getDate();
    if(mday<10)
      mday='0'+mday;
    var h = date.getHours();
    if(h<10)
      mday='0'+h;
    var min = date.getMinutes();
    if(min<10)
      min='0'+min;
    var sec = date.getSeconds();
    if(sec<10)
      sec='0'+sec;
        
    var now = year + '-' + mon +  '-' + mday + ' ' + h + ':' + min + ':' + sec;
    return now;
}

function check_email() {
    if( $('email') && ! $('email').value )
      {
        alert("Не указан email");
	$('comment_notice').checked = false;
      }	
}

function get_download() {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var pass = '';
    if($('file_password') && $('file_password').value) {
    	pass = $('file_password').value;
    }
    new Ajax.Request(
        '/adownload',
          {
             method: 'get',
             parameters: { download_id: $('download_id').value, id: $('file_id').value, pwd: pass, rand: randpar },

             onSuccess: function(oReq) {
                 eval('data=' + oReq.responseText);
                 if(data.status == "OK") {
		             if($('file_pwd_tr'))
    			         $('file_pwd_tr').hide();
	    	         var content = "<a href=# id=download_link>"+data.name+"</a>";
		             $('get_link_button').hide();
		             $('code_title').hide();
		             $('code_code').hide();
		             $('download_link').show();
		             Event.observe('download_link', 'click', function() {
			             //window.open('http://webproficlub.ru','_blank','');
    			         location.href = data.url;
	    	         });
                }
        		if(data.error == "wrong password") {
		            alert('Неверный пароль');
		        }
        		if(data.error == "wrong code") {
		            alert('Неверный код');
        		}
		        if(data.error == "no code") {
		            alert('Введите код');
        		}
             },
             onFailure: function () { }
          }
     );
}

function wyw_get_download() {
    var randpar = Math.round(10000*Math.random())+'0'+Math.round(10000*Math.random());
    var pass = '';
    if($('file_password') && $('file_password').value) {
	pass = $('file_password').value;
    }
    new Ajax.Request(
        '/adownload',
          {
             method: 'get',
             parameters: { wyw_file_id: $('file_id').value, pwd: pass, rand: randpar },

             onSuccess: function(oReq) {
                eval('data=' + oReq.responseText);
                if(data.status == "OK") {
		    if($('file_pwd_tr'))
			$('file_pwd_tr').hide();
		    var content = "<a href=# id=download_link>"+data.name+"</a>";
		    $('get_link_button').hide();
		    $('download_link').show();
		    $('download_link').href = data.url;
                }
		if(data.error == "wrong password") {
		    alert('Неверный пароль');
		}
             },
             onFailure: function () { }
          }
     );
}

function report_virus(id) {
    if(!id)
	return;
    new Ajax.Request(
        '/feedback',
          {
             method: 'get',
             parameters: { this_is_virus: 1, file_id: id },

             onSuccess: function(oReq) {
		alert('Ваша жалоба отправлена');
             },
             onFailure: function () { }
          }
     );
}

function show_settings(id) {
    $('FolderSettingsDiv'+id).show();
    $('folder_settings_'+id).hide();
}

function select_block(id) {
    if(Prototype.Browser.IE){
        var range = document.body.createTextRange();
        range.moveToElementText($(id));
        range.select();
    }
    else {
        if(Prototype.Browser.Gecko) {
            var range = document.createRange();
            range.selectNodeContents($(id));
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(range);
        }
    }
}

function select_input(id) {
    $(id).focus();
    $(id).select();
}

function switch_block(id) {
    if(visibility.get(id) == 1) {
        $(id).hide();
        visibility.set(id, 0);
    }
    else {
        $(id).show();
        visibility.set(id, 1);
    }
}

function mail_ru_download() {
    new PeriodicalExecuter(function(pe) {
        $('mail_ru_link').hide();
        $('real_link').show();
        pe.stop();
    }, 30);
    return true;
}

function download_delay(t,h) {
    if(!h || !document.getElementById('interval-link-time-pass'))
        return false;
    var tmpImg = new Image(), isrc = '/images/down_img_slow_link.jpg';
    tmpImg.src = isrc;
    download_timer = t||60;
    new PeriodicalExecuter(function(pe) {
        download_timer--;
        $('interval-link-time-pass').update(download_timer);
        if(download_timer<1) {
            $('interval-link-ads').hide();
            $('download-button-slow').addClassName('active').href=h;
            $('down-img-slow').src = isrc;
            pe.stop();
        }
    }, 1);
    return true;
}


function video_ads_switch_enable(t) {
    enable_timer = t||30;
    visibility.set('video_ads_block_part', 1);
    
    new PeriodicalExecuter(function(pe) {
        enable_timer--;
        if(enable_timer<1) {
            $('video-ads-block-hide').show();
            pe.stop();
        }
    }, 1);
}

function use_html_store(object, store_key) {
    if (object.innerHTML == '') {
	object.innerHTML = Store.get(store_key);
    } else {
	Store.set(store_key, object.innerHTML);
	object.innerHTML = '';
    }
    
    console.log(Store.get(store_key));
    console.log(object.innerHTML);
}

function video_ads_switch(sw) {
    var id = 'video_ads_block_part',
	vi = document.getElementById(id);
    
    use_html_store(vi, 'video_ads')
    switch_block(id);
    
    if (sw) {
	switch_block(sw);
    }
}

function flash_video_control(){
    var text = {0:'Посмотреть видео', 1:'Скрыть видео'},
	controll = document.getElementById('flash_video_controll'),
	object = document.getElementById('flash_video_object');
	
    //if (visibility.get('flash_video_object') == 1 || visibility.get('flash_video_object') == 0)
    use_html_store(object, 'video_object');

    if (Store.get('video_link') == 1) {
	Store.set('video_link', 0);	
    } else {
	Store.set('video_link', 1);
    }
    
    if (typeof visibility.get('flash_video_object') == 'undefined')
	visibility.set('flash_video_object', 1);
    	
    	
    controll.innerHTML = Store.get('video_link') == 1 ? text[0] : text[1];
    switch_block('flash_video_object');
}




