var editor = null;
var currentSite = []; 
var logedin = 'nie';
function tableSorterPagin(tableId){
var t = $("#workzonecontent").find(tableId).html(); 

if (t != null) $(tableId).dataTable({
"aaSorting": [[ 0, "desc" ]],
"sPaginationType": "full_numbers",
"oLanguage": {
      "sProcessing":   "Proszę czekać...",
      "sZeroRecords":  "Nie znaleziono żadnych pasujących indeksów",
			"sLengthMenu": "Pokaż _MENU_ pozycji na stronę",
			"sZeroRecords": "Nic nie znalazłem",
			"sInfo": "Pokazanych od _START_ do _END_ z _TOTAL_ pozycji",
			"sInfoEmtpy": "Pokazanych od 0 do 0 z 0 pozycji",
			"sInfoFiltered": "(znalezionych wśród _MAX_ wszystkich pozycji)",
			"sSearch":       "Szukaj:",
			"sUrl":          "",
        "oPaginate": {
        "sFirst":    "Pierwsza",
        "sPrevious": "Poprzednia",
        "sNext":     "Następna",
        "sLast":     "Ostatnia"
        }
		}
});
 
}

function sendAjaxForm(id,responseDiv)
{
$(id).ajaxForm({ 
        dataType:  'json', 
        // success identifies the function to invoke when the server response 
        // has been received 
        success:  function processJson(data) { 
        alert(data.message); 
        $(responseDiv).html(data.message);
        }
    }); 
}
function ajax_loading()
{
$("#content").html('<p class="loadingajax">Czytam dane...<br /><br /><img src="images/ajax-loader-circle.gif"/></p>');
}
function saveneewsletter()
{
  $("form#newsform .btn").click(function(){
  var this_form = $("#newsletter").html();
  if ($("#email").val()==''){
  return false;
  }
  $("#newsletter").addClas("loader");
  var dataString = 'email='+ $("#email").val();  
  //alert (dataString); return false;  
 
 $.ajax({  
   type: "POST",  
   url: "scripts/save_newsletter.php",  
   data: dataString,  
   success: function(data) {  
   $('#newsletter').html(data.message)  
     .hide()  
     .fadeIn(1500, function() {  
       $('#newsletter').append(this_form);  
     });  
   }  
 });  
 return false; 
  
  });
}
function ajax_request(where, what) {
  var nocache = Math.random();
  currentSite['url'] = what;
  if (what.indexOf('?') > 0 ) currentSite['cascheurl'] = what+'&nocache = '+nocache; else currentSite['cascheurl'] = what+'?nocache = '+nocache; 
  //alert(currentSite['cascheurl']);
  $(where).html('<p class="loadingajax">Czytam dane...<br /><br /><img src="./images/ajax-loader-circle.gif"/></p>');
  $.ajax({
           type : 'GET',
           url : currentSite["cascheurl"],
           
           success : function(data){
           $(where).html(data);
           if( $("textarea#Opis").length !=0)  createCKEditor('textarea#Opis');   
           },
           error : function(XMLHttpRequest, textStatus, errorThrown) {
           $(where).html('<p style="padding-top:50px;margin:auto;clear:both;"><h1>Wystąpił błąd podczas wczytywania strony</h1></p>');
           }
        });

parseLoginMenu(); 
}

function initMenu(what) {
  $(what+' ul').hide();
  //$(what+' ul:first').show();
  $(what+' li a').click(
    function() {
      var checkElement = $(this).next();
      if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
        return false;
        }
      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        $(what+' ul:visible').slideUp('normal');
        checkElement.slideDown('normal');
        return false;
        }
      }
    );
  }

function replaceDiv( div )
{
	if ( editor ) {
		editor.destroy();
  }
	
  editor = CKEDITOR.replace( div  ,
  {
  language:'pl',
  height:"300px",
  width:"98%",
  contentsCss:'./stylesheet/styleCkeditor.css',
  enterMode: CKEDITOR.ENTER_BR,
  shiftEnterMode:CKEDITOR.ENTER_P,  
  filebrowserBrowseUrl : './ckfinder/ckfinder.html',
 	filebrowserImageBrowseUrl : './ckfinder/ckfinder.html?type=Images',
 	filebrowserFlashBrowseUrl : './ckfinder/ckfinder.html?type=Flash',
 	filebrowserUploadUrl : './ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
 	filebrowserImageUploadUrl : './ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images',
 	filebrowserFlashUploadUrl : './ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash'

  } );
  
}

function createCKEditor(element){
  
  var content = $(element).val();
  //alert(content);
  
  if(CKEDITOR.instances["Opis"]) {
  
  delete CKEDITOR.instances["Opis"];
  
  } 
  
  CKEDITOR.replace('Opis',
    {
        height:"300px",
        enterMode: CKEDITOR.ENTER_BR,
        shiftEnterMode:CKEDITOR.ENTER_P,  
        toolbar :
        [
            ['Image','Table','HorizontalRule','SpecialChar','PageBreak','Iframe'],
            ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link','Unlink','Anchor','-','Source'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock']

        ],
       	filebrowserImageBrowseUrl : './ckfinder/ckfinder.html?type=Images',
 	     	filebrowserUploadUrl : './ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files',
 	      filebrowserImageUploadUrl : './ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images'
    });
    
  //CKEDITOR.instances["Opis"].content.setData(content);

}

function closeCKeditor(){

if ( editor ) {
		editor.destroy();
		//editor = null;
		//$("#cboxLoadingOverlay").css({display:'block'});
    }
 //$("#cboxLoadingOverlay").css({display:'none'});

}
function saveCKeditorData()
{
var editorHtml = editor.getData(""); 


if ( editor ) {
		editor.destroy();
		editor = null;
		}
$("#cboxSave").fadeOut('slow');
$("#cboxLoadingOverlay").css({display:'block'});

var ourlocation = location.href;
var thisstuff = ourlocation.split("?");
var id = thisstuff[1];
var idary = id.split("&");
var param3= idary[1];
idary = param3.split("=");
var currentsite = idary[1];


//alert(currentsite);
$.ajax({
            type : 'POST',
            url : './scripts/savesite.php',
            dataType : 'json',
            data: {
                bodysite : editorHtml,
                save:'save',
                file:currentsite
            },
            success : function(data){
           
            if(data.error === true) $("#cboxLoadingOverlay").css({'background-image':'none'}).append('<div id="messagediv"><h1>' + data.msg+ '</h1></div>')
                else {
                $("#cboxLoadingOverlay").css({display:'none'});
                } 
               
            },
            error : function(XMLHttpRequest, textStatus, errorThrown) {
              
                $("#cboxLoadingOverlay").css({'background-image':'none'}).append('<div id="messagediv"><h1>\Wystapił bład AJAX</h1></div>')
            }
        });


}
function openGallery(){
$(".gallery").colorbox({width:"1100px", height:"960px", overlaySave:false, iframe:true});
}
function editCKeditorfunction(site,hrefId){

$(".editcmd").colorbox({
          overlayClose:false,
          width:"80%",
          height:"100%",
          inline:true, href:"#content",
          onOpen:function(){},
					onLoad:function(){},
					onComplete:function(){
          replaceDiv("cboxLoadedContent");
          //replaceDiv("content");
          },
          onCleanup:function(){
          //closeCKeditor();
          },
          onSaved:function(){
          //closeCKeditor();
          saveCKeditorData();
          },
          onClosed:function(){
         
          }
  });
}
function openLoginform(){
$(".logincmd").colorbox({
          width:"380px;",inline:true, href:"#login_form",
          height:"250px",
          overlaySave:false,
          onOpen:function(){
          $("#login_form").load("./sites/forms/loginform.html");
          $("#login_form").css("display","block");
           },
					onComplete:function(){
          processLoginForm();
          },
          onCleanup:function(){
          $("#login_form").html("");
          }
					
					
  });

}
function openLogout(){
$(".logoutcmd").colorbox({
          width:"380px;",inline:true, href:"#login_form",
          height:"250px",
          overlaySave:false,
          onOpen:function(){
          $("#login_form").css("display","block");
          },
					onLoad:function(){},
					onComplete:function(){
           $("#login_form").fadeIn('fast');
           $.ajax({
           type : 'POST',
           dataType: 'json',
           url : './scripts/do-logout.php',
           data: ({logoutcmd : 'do-logout'}),
           success : function(data){
          
           if (!data.error) 
           {
           
           logedin='nie';
           $("#sessioninfo").html("");
           $("#login_form").html('<div style="padding-top:50px;font-size:16px;">'+data.msg+'</div>');
           $("#s_logoutcmd").css("display","none");
           $("#s_editcmd").css("display","none");
           $("#s_logincmd").css("display","inline");
           $("#adminpanel").css("display","none");
           } 
           
           //$.timeout(function(){
               $('#login_form').fadeOut(600,function() {
               $.fn.colorbox.close();
               location.href = 'index.php';
               });
                //location.href = 'index.php';
               //},800);
           },
           error : function(XMLHttpRequest, textStatus, errorThrown) {
         
          $("#login_form").html("<h1>Wystąpił błąd podczas wczytywania strony</h1>");
            }
        });
          },
          onCleanup:function(){
          //$("#login_form").html("");
          },
					onClosed:function(){},
					onSaved:function(){
         
          }
  });

}
function processLoginForm(){

$("form#login").submit(function(e){  

$('#submit').hide();
$('#ajax_loading').show();
var str = $(this).serialize();  
//alert(str);


$.ajax({  
    type: 'POST',
    url: './scripts/do-login.php',  // Send the login info to this page
    data: str,  
    success: function(msg){  
           $('#status').ajaxComplete(function(event, request, settings){  
           $('#submit').show();
           $('#ajax_loading').hide();  

        if(msg == 'OK') 
               {  
               
               $.timeout(function(){
               $('#cboxLoadedContent').fadeOut(600,function() {
               $.fn.colorbox.close();
               window.location.href = 'index.php';
               });
               location.href = 'index.php';
               },600);
           
              }  
        else // ERROR?
               {  
               var login_response = msg;
               $('#login_response').html(login_response);
               }  
      
        });  
    }  
   
  });
    
  return false;
}); // end submit event
}
function processEditPanel()
{
//var logedin = <? echo $_SESSION['zalogowany'];?> ;
//alert(logedin);
if (logedin=='tak') {

                $('#s_logoutcmd').css("display","inline");
                $('#s_editcmd').css("display","inline");
                $('#s_logincmd').css("display","none");
                 $('#adminpanel').css("display","inline");
} else {
                $('#s_logoutcmd').css("display","none");
                $('#s_editcmd').css("display","none");
                $('#adminpanel').css("display","none");
                $('#s_logincmd').css("display","inline");
        }
}
function highlitCurrentInput(){
      $("input").focus(function() {
			  $(this).parents('fieldset').css("background-color","red");
					
			});
			$("input").blur(function() {
			 $(this).parents('fieldset').css("background-color","");
					
			});
}

function parseLoginMenu(){

var noteditable = ["offerlist","editlist","add_house","add_flat","add_locale","add_commercial","add_square","requestform","contactform","offerdetail", "home","add_news"];
var occur;
var notedit;
var currents;
  for ( var i in noteditable )
    {
    
      currents = currentSite['url'];
      notedit = noteditable[i];
      if (logedin=='tak')
      {
        if (currents.indexOf(notedit) > 0)
        {
  
          $('#s_editcmd').css("display","none");
          return;
        }else $('#s_editcmd').css("display","inline"); 
      }  
    }
  
}

function processKwickMenu(){
$('.kwicks').kwicks({
					max : 170,
					spacing : 5
				});
}
/*
jQuery.fn.anchorAnimate = function(settings) {

 	settings = jQuery.extend({
		speed : 1100
	}, settings);	
	
	return this.each(function(){
		var caller = this
		$(caller).click(function (event) {	
			event.preventDefault()
			var locationHref = window.location.href
			var elementClick = $(caller).attr("href")
			
			var destination = $(elementClick).offset().top;
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
				window.location.hash = elementClick
			});
		  	return false;
		})
	})
}
*/
// google maps

function initializeMap(location) {
  var geocoder;
  //var map;
  var Impet = {
  map: null,
  infoWindow: null
 };
  Impet.closeInfoWindow = function() {
  Impet.infoWindow.close();
  };
  
  Impet.openInfoWindow = function(marker,content) {
  var markerLatLng = marker.getPosition();
  Impet.infoWindow.setContent([
    '<b>', content, '</b>'   
  ].join(''));
  Impet.infoWindow.open(Impet.map, marker);
  };
  
   
  geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 14,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
      //mapTypeId: google.maps.MapTypeId.HYBRID
    }
    Impet.map = new google.maps.Map(document.getElementById("google_map"), myOptions);
    
   
    //var address = locations; 
    //$('.address').contents().filter(function (){ return this.nodeType == 3;})[0].nodeValue;
    geocoder.geocode( { 'address': location}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        Impet.map.setCenter(results[0].geometry.location);
        var image = 'images/googlepushpin.png';
        var impetMarker = new google.maps.Marker({
        position:results[0].geometry.location ,
        map: Impet.map,
        icon: image,
        title:location

      });
        
      Impet.infoWindow = new google.maps.InfoWindow();
      google.maps.event.addListener(Impet.map, 'click', Impet.closeInfoWindow);
      google.maps.event.addListener(impetMarker, 'click', function() {
      Impet.openInfoWindow(impetMarker,location);
      });
      
      } else {
        alert("Nie rozpoznano adresu: " + status);
      }
    });
}

$().ready(function() {


      $("#slider ul li").css("display","block");
      logedin = $("#sessioninfo").html();
			processEditPanel();
      processKwickMenu();
			initMenu("#menu");
			initMenu("#adminmenu");
			//ajax_request("#content","./sites/home.html");
	    editCKeditorfunction("x","#editcmd");
      openLoginform();
      openLogout();
      //openGallery();

 
	$("#slider").easySlider({
				auto: true, 
				continuous: true,
				speed:'900',
				pause : 6000,
        controlsVisible: false
			});
      
  $("a.gallery").colorbox({
  rel:'gallery',
  overlaySave:false,
  transition:'fade', 
  speed:500,
  slideshow:true
  });    
   //$("#slider").css("display","box");
   
      //$("#kwick7").click(function(){
      //$("#slider2").show();
  //});
  
  $("#adminmenu li a").click(function(){
      $("#slider2").hide();
  });
  
  
  $('.newstitle').live('click',function(){
    var current = $(this).next().css('display');

    
  $('.newsdescription').each(function(){
  $(this).slideUp(500);
  });
  
  //alert(current);
  if (current=='none') {
    $(this).next().slideDown(500,function(){
    $('html,body').animate({scrollTop: $(this).prev().offset().top}, 500);
    });
  
  }
  
  //alert(p);
  });
  
  //newsletter
  
  $(".btn").live('click',function(){
  
  var this_form = $("#newsletter").html();
  /*
  if ($("#email").val()==''){
  //elaert($("#email").val());
  return false;
  }
  */
  
  var dataString = 'email='+ $("#email").val();  
  //alert (dataString);  
 
 $.ajax({  
   type: "POST",  
   url: "scripts/save_newsletter.php",  
   data: dataString,
   dataType:"json",  
   success: function(d) {  
   $('#newsletter').html(d.message).hide().fadeIn(2000, function() {  
    $('#newsletter').html(this_form).hide().fadeIn(2000);  
     });  
    //alert('ok');
    },
   error: function(){
      $('#newsletter').html("Wystąpił błąd zapisu!").hide().fadeIn(2000, function() {  
      $('#newsletter').html(this_form).hide().fadeIn(2000);  
     });  
   }  
 });
   
 //alert('ok');
 return false; 
 });
});
