/***************************************************************************
 * This file is a part of XnGine Content Management System                 *
 *						-------------------                                *
 * Copyright (C) 2005 by Michał Irzyk.                                     *
 *                                                                         *
 * $Id: JavaScripts.js                                                     *
 * This is JavaScript  functions libary                                    *
 ***************************************************************************/
       var clientPC = navigator.userAgent.toLowerCase();
       var browser = (parseInt(navigator.appVersion) >= 4) && ((clientPC.indexOf("msie") != -1)  || (clientPC.indexOf("opera") != -1))  && ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
       function PrivateMessage(text)
       {

         if(confirm(text))
         {
            location='UserPanel.php?do,ReadNewMessage';
         }
         else return false;

       }
       function open_window(windowUrl, width_size, height_size)
       {

         window.open(windowUrl,'newWindow','scrollbars=yes,width='+width_size+',height='+height_size+'left=100,top=100');
       }

       function SimpleTag(TagName, FormID, Description)
       {
 
            var PromptValue = window.prompt(Description);
			 
            if(!empty(PromptValue)){
    
					InsertText('['+TagName+']'+PromptValue+'[/'+TagName+']', FormID);
			
            }
            //else 	alert('Brak tekstu!' + PromptValue);
       }
       function PutTag(TagName, FormID, LanguageInfo)
       {
           	if (browser)
            {
        		theSelection = document.selection.createRange().text;
        		if (!theSelection)
                {
        			SimpleTag(TagName, FormID, LanguageInfo);
        		}
                else
                {
                    document.selection.createRange().text = '['+TagName+']'+theSelection+'[/'+TagName+']';
            		FormID.focus();
            		return;
        		}

        	}
            else
            {
                SimpleTag(TagName, FormID, LanguageInfo);
        	}
       }
       function AdvancedTag(FormID, desc_1, desc_2, code)
       {
            var var_1 = window.prompt(desc_1);
            if(!empty(var_1)) var var_2 = window.prompt(desc_2);

            code = code.replace('[VAR_1]', var_1);
            code = code.replace('[VAR_2]', var_2);
            if(!empty(var_1) && !empty(var_2))
            {
              InsertText(code, FormID);
            }
       }
       function OpenBMList()
	   {
	     window.open('Tools.php?do=ListBM','BookMarks','scrollbars=yes,width=400,height=300,left=100,top=100');
	   }
       function AddBookMark(SiteUrl, Description)
       {
            var PromptValue = window.prompt(Description);

            if(!empty(PromptValue))  window.open('Tools.php?do=AddBookMark&desc='+PromptValue+'&url='+SiteUrl,'show_news','scrollbars=yes,width=400,height=300,left=100,top=100');
            else AddBookMark(SiteUrl, Description);
       }
       function RedirectMainWindow(where)
	   {
	        opener.window.location=where; 	   
	   }
       function empty(varstring)
       {

         if((varstring!='') && (varstring!='null') && (varstring!='0') && (varstring!='undefined') && varstring.length>1)
         {
           return false;
         }
         else return true;
       }
       function InsertText(text2insert, FormID)
       {
          	  
			
			FormID = document.getElementById(FormID);

		   if (document.selection)
           {
       
			   FormID.focus();
               sel = document.selection.createRange();
               //sel.text2insert = text2insert;
               sel.text = text2insert;
           }
           else if (FormID.selectionStart || FormID.selectionStart == 0)
           {
			   var begin = FormID.selectionStart; //geting string begin cursor
               var end = FormID.selectionEnd; //geting string after cursor
               FormID.value = FormID.value.substring(0, begin) + text2insert + FormID.value.substring(end, FormID.value.length);
                
           }
           else
           {
               FormID.value += text2insert;
           }
        
       }
       function CheckAbility(dir)
       {
          var username = document.getElementById('user_nick').value;
          open_window(dir+'Tools.php?do,CheckNick,username,'+username, 400, 200);
       }

       function PopUpInsertText(text, FormID)
       {
           FormID = opener.document.getElementById(FormID);
          // opener.document.getElementById(FormID).value += text

           if (FormID.selection)
           {
               FormID.focus();
               sel = FormID.selection.createRange();
               sel.text = text;
           }
           else if (FormID.selectionStart || FormID.selectionStart == '0')
           {
               var begin = FormID.selectionStart; //geting string begin cursor
               var end = FormID.selectionEnd; //geting string after cursor
               FormID.value = FormID.value.substring(0, begin) + text + FormID.value.substring(end, FormID.value.length);
           }
           else
           {
               FormID.value += text;
           }
       }
       function useNick(FormID)
       {
           alert(getElementById('UsersSelect'));
           //var user = getElementById('UsersSelect').options[getElementById('UsersSelect').selectedIndex].value;
           //opener.document.getElementById(FormID).value='';
           alert(user);
           PopUpInsertText(user, FormID);
           window.close();
           return false;
       }

       function SelectCheckboxes(FormID)
       {
        	if (FormID)
        	{
        		for (var i=0;i<FormID.length;i++)
        		{
        			if (FormID[i].type=='checkbox')
        				FormID[i].checked=!FormID[i].checked;
        		}
        	}


       }
       function HideBBCode(FormID, desc_1, desc_2)
       {
                var hide_title = window.prompt(desc_1);

            if (browser)
            {
        		theSelection = document.selection.createRange().text;
        		if (!theSelection)
                {
                    
					var hide_text = window.prompt(desc_2);                    
                   	InsertText('[hide='+hide_title+']'+hide_text+'[/hide]', FormID);
                    
        		}
                else
                {
                    document.selection.createRange().text = '[hide='+hide_title+']'+theSelection+'[/hide]';
            		FormID.focus();
            		return;
        		}

        	}
            else
            {
                var hide_text = window.prompt(desc_2);
                InsertText('[hide='+hide_title+']'+hide_text+'[/hide]', FormID);

        	}

       }
   
       function confrim_action(Question, Link)
       {
        	if(confirm(Question))
        	{
                window.location=Link;
        	}
       }

       function InsertImage(text, FormID)
       {
           if(!empty(document.XForm.site.value)) PopUpInsertText(" [align=" + document.XForm.site.value+ "][image]" + text +  "[/image][/align] ", FormID);
           else PopUpInsertText("[image]" + text +  "[/image]", FormID);
       }
       
       function SearchUser(FormID, filename)
       {
            open_window(filename+'?do,SearchUser,FormID,'+FormID, 400, 200);

       }
       function change_preview(object, dir)
       {
            document.getElementById('preview').src = '../Uploads/'+dir+'/'+object;
       }
       function menu(id_one)
       {
                if(document.getElementById(id_one).style.display == 'inline')
                      document.getElementById(id_one).style.display = 'none';
                else
                      document.getElementById(id_one).style.display = 'inline';
       }
		function ZoomIn(element, n_width, n_height)
	    {
					element = document.getElementById(element);
					element.style.width = (n_width*1.5) +'px';
					element.style.height =(n_height*1.5)+ 'px';
		   	        //element.style.filter = "alpha(opacity:"+100+")";
		}
	    function ZoomOut(element,  n_width, n_height)
		{
					element = document.getElementById(element);
					element.style.width = n_width + 'px';
					element.style.height = n_height + 'px';
				  //element.style.filter = "alpha(opacity:"+85+")";
		}
       function OnKeyGo(e,next,prev)
       {
           if(!e) var e = window.event;
           if(e.keyCode) e = e.keyCode;
           else if(e.which) e = e.which;
           switch( e )
           {
               case 37:
                   if(prev) window.location =prev;
                   break;
               case 39:
                   if(next) window.location =next;
                   break;
           }
       }
       function ShowHide(DivID)
       {
           if(document.getElementById(DivID).style.display == 'block')
               document.getElementById(DivID).style.display = 'none';
           else
              document.getElementById(DivID).style.display = 'block';
        }
     
function SelectTag(FormID, SelectID, tag){
   
   SelectID = document.getElementById(SelectID);
  //OnChange="if(this.options[this.selectedIndex].value != "'.$lang.'"){ document.language_select.submit() }"
  v = (SelectID.options[SelectID.selectedIndex].value);
  if(!empty(v)){
	FormID = document.getElementById(FormID);
   	if (browser)
            {
        		theSelection = document.selection.createRange().text;
        		if (!theSelection)
                {
        			
					alert('Zaznacz tekst');
					 /*PromptValue = window.prompt('podaj wartosc');
					 SimpleTag(TagName, FormID, LanguageInfo);
					 InsertText('['+tag+'='+v+']'+PromptValue+'[/'+tag+']', FormID);*/
					
        		}
                else
                {
                  
					document.selection.createRange().text = '['+tag+'='+v+']'+theSelection+'[/'+tag+']';
            		FormID.focus();
            		return;
        		}

        	}
            else
            {
                //SimpleTag(TagName, FormID, LanguageInfo);
                alert('Twoja przegladarka nieobsluguje tej opcji');
        	}
    }
}
function modifyPoints(){
	var points = window.prompt('Wpisz punkty jakie chcesz dodać lub odjać (np. 10, -20)');
	var oldpoints = document.getElementById('user_points').value;

	var newPoints = (parseInt(oldpoints)+parseInt(points));
	 if(confirm('Punkty obecne:'+oldpoints+"\n"+'Punkty po modyfikacji ('+points+'): '+newPoints+"\n Zgadza się?"))
     {
        document.getElementById('user_points').value = (parseInt(oldpoints)+parseInt(points));
     }
      
}
function disableForm(theform) {
if (document.all || document.getElementById) {
for (i = 0; i < theform.length; i++) {
var tempobj = theform.elements[i];
if (tempobj.type.toLowerCase() == "submit" || tempobj.type.toLowerCase() == "reset")
tempobj.disabled = true;
}
return true;
}
else {
return false;
}
}

/* DRAFT 1.0 RC1 31.07.2009 */

function SaveDraft()
{
			
			var url='http://cc-series.pl/Ajax.php';
			var met = $('#'+Form).attr('method');	
			var data='do=save&v28='+type;			
			$('#'+Form+' :input').each
			(
				function (elementIndex){
					var name = $(this).attr('name');
					var value = $(this).val();
					if(name.length>2){
						data += '&'+name+'='+value.replace('&','and');//
					}
					
				}
			);
		
			$.ajax
			(
				{					
					type: met,
					url: url,
					data: data,
 
					error: function (XMLHttpRequest, textStatus, errorThrown)
					{
						$("#message").show();
						$("#message").append('Błąd obiektu o nazwie:'+XMLHttpRequest+'<br />Komunikat:'+textStatus+'<br />Rodzaj:'+ errorThrown);
					},
					success: function(html)
					{
						$('#message').html(html);
						$("#message").css({'background-color' : '#ADFF2F', 'border' : '1px solid #556B2F;', 'margin': '1em 5% 10px;', 'margin' : '1em 5% 10px;padding: 0 1em 0 3em;'} );
					}
				}
			); 			
			
	}
function DropDraft(){
	if(confirm('Czy na pewno chcesz usunąć?')){
		var url='http://cc-series.pl/Ajax.php';
		$.ajax
				(
					{					
						type: 'POST',
						url: url,
						data: 'do=drop&v28='+type, 		
						success: function(html)
						{
							$('#message').html(html);
							$("#message").css({'background-color' : '#FFA07A', 'border' : '1px solid #8B0000;', 'margin': '1em 5% 10px;', 'margin' : '1em 5% 10px;padding: 0 1em 0 3em;'} );
								setInterval("SaveDraft();", 30000);						
						}
					}
				); 
	}
}
	
function CheckDraft(){

	var url='http://cc-series.pl/Ajax.php';
	var met = 'POST';				
	var data='do=check&v28='+type;
	$.ajax
			(
				{					
					type: met,
					url: url,
					data: data,
 
					error: function (XMLHttpRequest, textStatus, errorThrown)
					{
						$("#message").show();
						$("#message").append('Błąd obiektu o nazwie:'+XMLHttpRequest+'<br />Komunikat:'+textStatus+'<br />Rodzaj:'+ errorThrown);
					},
					success: function(html)
					{
						$('#message').html(html);
						if(html.length>2){
		
						$("#message").css({'background-color' : '#CFEBF7', 'border' : '1px solid #2580B2;', 'margin': '1em 5% 10px;', 'margin' : '1em 5% 10px;padding: 0 1em 0 3em;'} );
					
						}
						else{
							setInterval("SaveDraft();", 30000);						
						}
					}
				}
			); 
}
function RestroreDraft(){
	for (key in post){
			$('#'+key).val(post[key]);			
	}
	if(post.length <1){
	$("#message").css({'background-color' : '#ADFF2F', 'border' : '1px solid #556B2F;', 'margin': '1em 5% 10px;', 'margin' : '1em 5% 10px;padding: 0 1em 0 3em;'} );
	$("#message").html('Hurra, Draft został przywrócony!');
	}
	else{
		$("#message").css({'background-color' : '#FFA07A', 'border' : '1px solid #8B0000;', 'margin': '1em 5% 10px;', 'margin' : '1em 5% 10px;padding: 0 1em 0 3em;'} );
		$("#message").html('Ooops, pojawił się błąd w odzyskiwaniu kopii zapasowej.');
	}
}
/* RESIZE IMAGES  1.0 RC1 31.07.2009 */
function Thumnalizer(divID, maxWidth, maxHeight){
 var ratio = 0;  
 
 $('#'+divID+' img').each(function() {
 
        var width = $(this).width();    
        var height = $(this).height();  
		var thumb = false;
		var newHeight =height;
		var newWidth = 0;
	    if (width > maxWidth){
            ratio = maxWidth / width;   
            height = height * ratio;    
			thumb = true;
			newHeight = Math.floor(height);
			newWidth = maxWidth;
        }
		if (newHeight > maxHeight ){
            ratio = maxHeight / height; 
            width = width * ratio; 					
			thumb = true;
			newHeight = maxHeight;
			newWidth = Math.floor(width);
       }
		//alert($(this).attr("src")+$(this).width()+'x'+$(this).height());
		if(thumb){	
			$(this).wrap('<div class="thumb-img" style="width:'+newWidth+'px; height:'+newHeight+'px;"><div class="thumb-inner"><a href="'+$(this).attr( "src" )+'"  rel="thumbnail" target="_blank">' + '</a></div><div class="thumb-strip" style="width:'+newWidth+'px;">Kliknij, aby powiększyć</div><div class="thumb-zoom"></div></div>');
		}
    });	
}


/* MESSAGES 1.0 RC1 12.11.2009 */

function GetInfos() {
	
	/*
	document.getElementsByTagName('html')[0].setAttribute('style','margin-top:22px;');
	*/
		
	/*var DownloadStrip = document.createElement("div")'
		DownloadStrip.setAttribute('id','Message');
		DownloadStrip.setAttribute('style', 'display:none;top:0;right:0;width:500px;color:#F2E4E4;background-color:#C82828;border:1px solid #8C8C8C;padding:10px; z-index: 5;');
	  //GetInfos();*/
	 // $('#content').prepend('<div id="Message" style="display:none;width:500px;color:#F2E4E4;background-color:#C82828;border:1px solid #8C8C8C;padding:10px;display:inline;"></div>');
	  $.ajax({ type: 'GET',
			 url: 'messages.class.php?do=GetInfos',					
			 success: function(html)	{
							if(html!='false'){ 
								$('#Message').show();								
								 $('#Message').html(html);
							}
				}
			}
		); 
	  
	  
	 // document.getElementsByTagName('html')[0].appendChild(DownloadStrip);
}

function GenerateMessage(type){
	/* 1=>'Zgloszono martwy link w dziale download',
			2=>'Otrzymano wiadomosc E-Mail ',
			3=>'Użytkownik napisał newsa i prosi o jego akceptacje',
			4=>'Zgłoszono błędy na stronie'
		*/
		//alert(type);
	var datastring = '';
	switch(type){
		case '1':
			//alert('wybrales 1');
			datastring = 'do=PutMessage&type=1&url='+window.location+'&comment='+$('#message').val();
			break;
		case '2':
		
			
			var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
			if (!filter.test($('#email').val())) {
				$('#email').css({'border':'2px solid #C82828','background-color':'#FFCCCC'});
				alert('Proszę podać E-Mail kontaktowy');
				$('#email').focus();
				return false;
			}
			else{
				$('#email').css({'border':'0','background-color':'#E1FFCC'}); 
			}
			if($('#message').val().length<10){
				$('#message').css({'border':'2px solid #C82828','background-color':'#FFCCCC'});
				alert('Proszę podać treć wiadomoci');
				$('#message').focus();
				return false;
			}
			else{
				$('#message').css({'border':'0','background-color':'#E1FFCC'}); 
			}
			datastring = 'do=PutMessage&type=2&comment='+$('#message').val()+'&email='+$('#email').val();
			break;

		case '4':
			
			if($('#message').val().length<10){
				$('#message').css({'border':'2px solid #C82828'/*,'background-color':'#FFCCCC'*/});
				alert('Proszę podać opis błędu');
				$('#message').focus();
				return false;
			}
			datastring = 'do=PutMessage&type=2&comment='+$('#message').val()+'&email='+$('#email').val();
			break;
			
		default:
			datastring = 'Type:'+type+'a';
			//break;
	}
	//alert(datastring);
	$.ajax({ type: 'POST',
		 url: 'messages.class.php',					
		 data: datastring, 
		 success: function(html){	$('#msg').html(html);		}
		} 
	); 
	//alert(data);

}
function ChangeStatus(id){
$.ajax({ type: 'POST',
		 url: 'messages.class.php',					
		 data: 'do=SaveStatus&id='+id, 
		 success: function(html){	if(html=='true'){ $('#Status').css({'background-color':'#FFCCCC', 'border': '1px solid #B40606'}); $('#Status').html('Hurra, sprawę uznano jako rozwišzanš'); }
		 else { $('#Status').html(html); }		}
		} 
	); 

}
function HideMsg(){
	$('#msg').hide();
}
function GetForm(type){

$.ajax({ type: 'GET',
		 url: 'messages.class.php?do=ShowForm&type='+type,					
		 success: function(html){	$('#msg').show(); $('#msg').html(html);	/*$('#msg').css({'color':'silver','width':'600px','position':'ablosute','background-color':'#2c2c2c'});*/	}
		} 
	); 

}
;
  	 