
/* Main Template: */
function openWin(url,title,attrib) {
	return window.open(url,title,attrib);
}
function openInnewWindow(url,width,height,toolbar) {
	if(toolbar==1) {
		openWin(url,'darkonet','toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,width='+width+',height='+height)
	 }
	 else {
		openWin(url,'darkonet','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,movable=yes,resizable=no,width='+width+',height='+height)
	}
}

function urlChangeParam(pname,pval,url) {
   url=(typeof(url)=='undefined')?window.location.href:url;
   var url_parts=url.split('?',2);
   var url_search=(url_parts.length==2)?'?'+url_parts[1]:'';
   var new_url=null;
   var r=new RegExp('([?&]'+pname+'=)([^?&#]*)');
   var r1=new RegExp('(\\?'+pname+'=)([^?&#]*)');
   var r2=new RegExp('(&'+pname+'=)([^?&#]*)');
   if (pval==null)
   {
      new_url=url.replace(r1,'?');
      new_url=new_url.replace(r2,'');
      if (new_url.substr(new_url.length-1,1)=='?')
      	new_url=new_url.substr(0,new_url.length-1);
   }
   else if (url_search.search(r)!=-1)
      new_url=url.replace(r,'$1'+encodeURIComponent(pval));
   else
      new_url=url+((url_search=='')?'?':'&')+pname+'='+encodeURIComponent(pval);
   return new_url;
}
function openLayer(button_id,layer_id,direction) {
   var button_obj=document.getElementById(button_id);
   var but_left=button_obj.offsetLeft;
   var elm=button_obj;
   while (elm=elm.offsetParent)
      but_left+=elm.offsetLeft;
   var but_right=but_left+button_obj.offsetWidth;
   var but_top=button_obj.offsetTop;
   var elm=button_obj;
   while (elm=elm.offsetParent)
      but_top+=elm.offsetTop;
   var but_bottom=but_top+button_obj.offsetHeight;

   var layer_obj=document.getElementById(layer_id);
   layer_obj.style.display='';
   layer_obj.style.left=((direction=='left')?(but_left):(but_right-layer_obj.offsetWidth))+'px';
   layer_obj.style.top=but_bottom+'px';
}
function closeLayer(layer_id) {
   document.getElementById(layer_id).style.display='none';
}
function showHelpBox(evt,itm_id) {
   var box=document.getElementById(itm_id);
   var box_width=parseInt(box.style.width);
   var go_x=document.body.scrollLeft+evt.clientX-box_width-10;
   var go_y=document.body.scrollTop+evt.clientY+10;
   box.style.left=go_x;
   box.style.top=go_y;
   box.style.display='block';
}
function hideHelpBox(itm_id) {
   var box=document.getElementById(itm_id);
   box.style.display='none';
}

//operation_data: op={operation}[&...]
function doRemoteOperation(operation_data,post_data,is_full_path) {
   var _makeQueryPostString=function(cvar,arr_var) {
         var pstr='';
         var i;
         for (i in arr_var) {
            if (typeof(arr_var[i])=="object")
               pstr=pstr+_makeQueryPostString(cvar+'['+i+']',arr_var[i]);
            else
               pstr=pstr+'&'+cvar+'['+i+']='+encodeURIComponent(arr_var[i]);
         }
         return pstr;
      }
   var rq=null;
   if (window.XMLHttpRequest)
		rq = new XMLHttpRequest();
	else {
		try { rq = new ActiveXObject('Microsoft.XMLHTTP'); }
		catch (e) { rq=null; }
	}
	if (!rq)
	   return false;
   var post_string=(typeof(post_data)!='undefined')?_makeQueryPostString('data',post_data):'';
   var send_url='/_remote_op.php'+((!is_full_path)?window.location.pathname+'?'+operation_data:operation_data);
	rq.open("POST",send_url,false);
	rq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	rq.setRequestHeader("Charset","UTF-8");
	rq.send(post_string);
//alert(send_url+'\n'+rq.responseText);
   return rq.responseText;
}

function player(v,c,o,i) {
	openWin("/player.php?v="+v+((c!="")?"&c="+c:"")+((o!="")?"&o="+o:"")+((i!="")?"&i="+i:""),"player","toolbar=no, alwaysRaised=yes, location=no, titlebar=no, directories=no, status=no, menubar=no, scrollbars=no, movable=yes, resizable=no, width=640, height=430");
}


/* Operations: */
function submitTVSearch(srform) {
	var sr_url='';
	sr_url+=srform.srin.options[srform.srin.selectedIndex].value+'?op=search';
	sr_url=urlChangeParam('sr',srform.sr.value,sr_url);
	sr_url=urlChangeParam('srde',((srform.srde.checked)?'1':'0'),sr_url);
	sr_url=urlChangeParam('srcr',((srform.srcr.options[srform.srcr.selectedIndex].value!='')?srform.srcr.options[srform.srcr.selectedIndex].value:null),sr_url);
	sr_url=urlChangeParam('srpe',((srform.srpe.options[srform.srpe.selectedIndex].value!='')?srform.srpe.options[srform.srpe.selectedIndex].value:null),sr_url);
	sr_url=urlChangeParam('srwa',((srform.srwa.options[srform.srwa.selectedIndex].value!='')?srform.srwa.options[srform.srwa.selectedIndex].value:null),sr_url);
	sr_url=urlChangeParam('srtp',((srform.srtp.options[srform.srtp.selectedIndex].value!='')?srform.srtp.options[srform.srtp.selectedIndex].value:null),sr_url);
	window.location=sr_url;
	return false;
}
function submitDeleteCategory(qstr,refresh_location) {
   var res=doRemoteOperation(qstr,null,true);
   if (!res || res=='0')
      alert('שגיאה: התחנה/הערוץ לא נמחקו.');
   else
   {
   	  if (refresh_location!=window.location.href)
   	     window.location=refresh_location;
   	  else
         window.location.reload();
   }
}
function submitDeleteCategoryFromCategory(qstr,refresh_location) {
   var res=doRemoteOperation(qstr,null,true);
   if (!res || res=='0')
      alert('שגיאה: התחנה/ערוץ/סדרה לא הוסרו.');
   else
   {
   	  if (refresh_location!=window.location.href)
   	     window.location=refresh_location;
   	  else
         window.location.reload();
   }
}
function submitDeleteMovie(qstr) {
   var res=doRemoteOperation(qstr,null,true);
   if (!res || res=='0')
      alert('שגיאה: התוכנית לא נמחקה.');
   else
      window.location.reload();
}
function submitDeleteMovieFromCategory(qstr) {
   var res=doRemoteOperation(qstr,null,true);
   if (!res || res=='0')
      alert('שגיאה: התוכנית לא הוסרה.');
   else
      window.location.reload();
}
function submitUserSubscribe(sub_act) {
   var res=doRemoteOperation('op=usr_subscribe&sb='+sub_act);
   if (!res || res=='0')
      alert('מצטערים, לא ניתן לבצע את בקשתך.');
   else
      window.location.reload();
}
function submitCutMovie(vid) {
   var res=doRemoteOperation('op=do_cut&vid='+vid);
   if (!res || res=='0')
      alert('שגיאה: לא ניתן לגזור.');
   else
      window.location.reload();
}
function submitCopyMovie(vid) {
   var res=doRemoteOperation('op=do_copy&vid='+vid);
   if (!res || res=='0')
      alert('שגיאה: לא ניתן להעתיק.');
   else
      window.location.reload();
}
function submitCutCategory(cid) {
   var res=doRemoteOperation('op=do_cut&cid='+cid);
   if (!res || res=='0')
      alert('שגיאה: לא ניתן לגזור.');
   else
      window.location.reload();
}
function submitCopyCategory(cid) {
   var res=doRemoteOperation('op=do_copy&cid='+cid);
   if (!res || res=='0')
      alert('שגיאה: לא ניתן להעתיק.');
   else
      window.location.reload();
}
function submitPaste(ord) {
   var res=doRemoteOperation('op=do_paste'+((ord!=null)?'&ord='+ord:''));
   if (!res || res=='0')
      alert('שגיאה: לא ניתן להדביק.');
   else
      window.location.reload();
}

function getMovieCategoriesList(vid) {
	var rq=null;
	if (window.XMLHttpRequest)
		rq = new XMLHttpRequest();
	else {
		try { rq = new ActiveXObject('Microsoft.XMLHTTP'); }
		catch (e) { rq=null; }
	}
	if (!rq)
		return false;
	var send_url='/_remote_get_mov_catlist.php?vid='+vid;
	rq.open("GET",send_url,false);
	rq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	rq.setRequestHeader("Charset","UTF-8");
	rq.send(null);
	return rq.responseText;
}

var intro_timer=null;
function showCategoryIntroduction(intro_ticks,intro_id,hide_id,intro_ticker_id) {
	if (intro_ticks>0) {
		document.getElementById(hide_id).style.display='none';
		document.getElementById(intro_id).style.display='';
		document.getElementById(intro_ticker_id).innerHTML=intro_ticks;
		intro_timer=window.setTimeout("showCategoryIntroduction("+(intro_ticks-1)+",'"+intro_id+"','"+hide_id+"','"+intro_ticker_id+"');",1000);
	}
	else if (intro_ticks==0) {
		document.getElementById(intro_id).style.display='none';
		document.getElementById(hide_id).style.display='';
		intro_timer=null;
	}
}
function skipCategoryIntroduction(intro_id,hide_id) {
	if (intro_timer)
		window.clearTimeout(intro_timer);
	document.getElementById(intro_id).style.display='none';
	document.getElementById(hide_id).style.display='';
}


/* Auto Complete */
// Object AutoComplete: params: ac_ac_func= func(str,max) the function name ; ac_textbox= the text-box input id ; ac_listbox= the list-box element id ; ac_listbox_inner= the inner list-box id in which show the results (defaults: ac_textbox_id)
function AutoComplete(ac_ac_func_str,ac_textbox_id,ac_listbox_id,ac_listbox_inner_id) {
    /*init the AC:*/
    this.textbox=document.getElementById(ac_textbox_id);
    this.listbox=document.getElementById(ac_listbox_id);
    this.listbox_inner=(ac_listbox_inner_id)?document.getElementById(ac_listbox_inner_id):this.listbox;
    this.ac_func_str=ac_ac_func_str;
    this.ac_max=25;  //max results in the list
    this.ac_min_word_len=1;  //min word length to make auto-complete
    this.ac_interval=0;  //the mseconds to wait since text changes to get auto-complete suggestions
    this.open_timeout=null;  //timeout object of open
    //attach handlers:
    if (this.listbox && this.textbox) {
        this.listbox._AC=this;
        this.textbox._AC=this;
        this.textbox.onkeyup=function() {
            this._AC.openACList(this.value);
        }
        this.textbox.onfocus=function() {
            this._AC.openACList(this.value);
        }
	    this.textbox.onblur=function() {
		    this._AC.closeACList();
        }
    }
}
AutoComplete.prototype.openACList=function(str) {
    if (str.length<this.ac_min_word_len)  //if less than minimum to complete
        return this.closeACList();
    this.open_timeout=setTimeout('document.getElementById(\''+this.listbox.id+'\')._AC.showACList(\''+str.replace('\\','\\\\').replace('\'','\\\'')+'\','+this.ac_func_str+'(\''+str+'\','+this.ac_max+'));',this.ac_interval);
}
AutoComplete.prototype.showACList=function(str,ac_results) {
    if (this.open_timeout) {
        clearTimeout(this.open_timeout);
        this.open_timeout=null;
    }
    openLayer(this.textbox.id,this.listbox.id,'left');
    this.listbox_inner.innerHTML='<span style="color:#090909;"><i>טוען...</i></span>';
    var results_div=document.createElement('DIV');
    var i;
    for (i=0; i<ac_results.length; i++) {
        var elem=document.createElement('DIV');
        elem._AC_value=ac_results[i];
        elem._AC=this;
        elem.innerHTML=ac_results[i].slice(0,str.length).bold()+ac_results[i].slice(str.length);
        elem.style.cursor='default';
        elem.onmousedown=function(evt) {
            this._AC.textbox.value=this._AC_value;
        }
        elem.onmouseover=function() {
            this.style.backgroundColor='#fff9ff';
        }
        elem.onmouseout=function() {
            this.style.backgroundColor='';
        }
        results_div.appendChild(elem);
    }
    if (ac_results.length==0)
        results_div.innerHTML='<div style="color:#666666;" align="center"><i>אין התאמות</i></div>';
    this.listbox_inner.innerHTML='';
    this.listbox_inner.appendChild(results_div);
}
AutoComplete.prototype.closeACList=function() {
    if (this.open_timeout)
        clearTimeout(this.open_timeout);
    closeLayer(this.listbox.id);
}

// Object AutoCompleteDB: the passed array of values must be sorted!
function AutoCompleteDB(ac_db) {
    this.db=ac_db;  //the db object sorted array of values
    this.index_levels=3;  //tree levels to index
    this.num_values=0;  //number of values indexed
    this.end_of_value=false;  //indicates if this index represents an end of a value string
}
AutoCompleteDB.prototype.getAutoCompleteValues=function(str,max) {
    /* assuming this.ac_db is sorted! */
    var ac_arr=new Array();
    var pos=0,max_pos=str.length-1;
    var char_code=str.toLowerCase().charCodeAt(pos),char_code_val;
    var i;
    for (i in this.db) {
        if (this.db[i].toLowerCase().indexOf(str.toLowerCase().slice(0,pos))!=0)  //no more matches
            break;
        char_code_val=this.db[i].toLowerCase().charCodeAt(pos);
        while (char_code==char_code_val && pos<max_pos) {
            pos++;
            char_code=str.toLowerCase().charCodeAt(pos);
            char_code_val=this.db[i].toLowerCase().charCodeAt(pos);
        }
        if (char_code==char_code_val && pos==max_pos) {  //matched at the end
            ac_arr.push(this.db[i]);
            if (ac_arr.length>=max)
                break; 
        }
    }
    return ac_arr;
}
