var APP_DOMAIN  = 'www.m7club.pl';
var MENU_TAB_ID = '';

$.fn.rating.options.required  = true; // Wyłącz button "Cancel"
$.fn.rating.options.half      = true; // Głosowanie co 0.5 pkt
$.fn.rating.options.starWidth = 16;

Array.prototype.inArray = function(v)
{
  for(var i = 0, l = this.length; i < l; i++)
  {
    if(this[i] == v)
        return true;
  }
  return false;
}


addComment = {
	showForm : function(commId) {
		var t = this, div, comm = t.I('comment-'+commId), respond = t.I('respond'), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent_id');
        
		if ( ! t.I('post-comment-temp-form-div') ) {
			div = document.createElement('div');
			div.id = 'post-comment-temp-form-div';
			div.style.display = 'none';
			respond.parentNode.insertBefore(div, respond);
		}
		comm.parentNode.insertBefore(respond, comm.nextSibling);
        
        t.I('commentHeader').innerHTML = 'Dodaj odpowiedź na ten komentarz';
		
        if ( parent )
            parent.value = commId;
		cancel.style.display = '';
        
		cancel.onclick = function() {
			var t = addComment, temp = t.I('post-comment-temp-form-div'), respond = t.I('respond');
            
			if ( ! temp || ! respond )
				return;
            
            t.I('commentHeader').innerHTML = 'Dodaj nowy komentarz';
            
			temp.parentNode.insertBefore(respond, temp);
			temp.parentNode.removeChild(temp);
			this.style.display = 'none';
			this.onclick = null;
			return false;
		}
		try { t.I('comment').focus(); }
		catch(e) {}
		return false;
	},
	I : function(e) {
		return document.getElementById(e);
	}
}



_calendar = function(d)
{
  $("#kalendarz-imprez").fadeTo("fast", 0.33);
  
  var req = "calendarDate="+d+"&mode=ajax&rand="+(new Date()).getTime();
  
  $.ajax({
  url    : "/cgi-bin/index.pl",
  type   : "POST",
  data   : req,
  success: function(r){
    //alert( $("#kalendarz-imprez").html() )
    //div.innerHTML = r;
    $("#kalendarz-imprez").fadeTo("fast", 1).html(r);
    calendarTip();
  },
  error: function(){ alert("Serwer nie odpowiada, odśwież stronę i spróbuj ponownie!") }
  });
}

_evanetDate = function(d)
{
  window.location.href="/imprezy/"+d+".html";
}


calendarTip = function()
{
  if($(this).data("qtip")) $(this).qtip("destroy");
  
  $(".cssSpecialDays").each(function(){
    
    //var bg = (this.className.match(/Off/)) ? '#d9d9d9' : '#a0aebf'
    //var bc = (this.className.match(/Off/)) ? '#afafaf' : '#5b7593'
    $(this).qtip({
    content: $(this).attr('tooltip'),
    style: {
      border: {
        width: 5,
        radius: 10,
        color: '#5b7593'
      },
      padding: 6,
      color: '#ffffff',
      background: '#a0aebf',
      fontSize: '11px',
      fontFamily: 'Tahoma,Arial',
      lineHeight: '17px',
      textAlign: 'justify',
      width: 300,
      tip: true,
      name: 'cream'
    },
    show: {
      solo: true,
      delay: 0
    },
    position: {
      corner: {
        tooltip: 'rightMiddle',
        target: 'leftMiddle'
      },
      adjust: {
        screen: true
      }
    }
  })});
}



$(document).ready(function(){
    $("#boxLoginForm").submit(function(){
        if($("#box_authorize_login").val().length==0)
        {
            alert("Podaj swoją nazwę użytkownika!");
            $("#box_authorize_login").focus();
            return false;
        }
        if(!/^[a-zA-Z0-9\._-]+$/.test($("#box_authorize_login").val()))
        {
            alert("Podałeś nieprawidłową nazwę użytkownika. Upewnij się, że wpisałeś poprawnie swój login!");
            $("#box_authorize_login").focus();
            return false;
        }
        if($("#box_authorize_password").val().length==0)
        {
            alert("Wpisz hasło, które służy Ci do logowania się na konto w serwisie!");
            $("#box_authorize_password").focus();
            return false;
        }
        return true;
    });
    
    $("#loginForm").submit(function(){
        if($("#authorize_login").val().length==0)
        {
            alert("Podaj swoją nazwę użytkownika!");
            $("#authorize_login").focus();
            return false;
        }
        if(!/^[a-zA-Z0-9\._-]+$/.test($("#authorize_login").val()))
        {
            alert("Podałeś nieprawidłową nazwę użytkownika. Upewnij się, że wpisałeś poprawnie swój login!");
            $("#authorize_login").focus();
            return false;
        }
        if($("#authorize_password").val().length==0)
        {
            alert("Wpisz hasło, które służy Ci do logowania się na konto w serwisie!");
            $("#authorize_password").focus();
            return false;
        }
        return true;
    });
    
    
    $("#boxResetPasswordForm").submit(function(){
        if($("#box_reset_login").val().length==0 && $("#box_reset_email").val().length==0)
        {
            alert("Podaj nazwę użytkownika lub adres e-mail, użyty podczas rejestracji!");
            $("#box_reset_login").focus();
            return false;
        }
        return true;
    });
    
    $("#lostPasswordLink").click(function(){
        $("#loginPanelBox").fadeOut("medium", function(){
            $("#lostPasswordPanelBox").fadeIn("medium", function(){
                $("#box_reset_login").focus();
            });
        });
        return false;
    });
    $("#lostPasswordBackLogin").click(function(){
        $("#lostPasswordPanelBox").fadeOut("medium", function(){
            $("#loginPanelBox").fadeIn("medium", function(){
                $("#box_authorize_login").focus();
            });
        });
        return false;
    });
    
    $("#boxPollForm").submit(function(){
        if(!$('#boxPollForm input[@name="answer"]').is(":checked"))
        {
            alert("Zaznacz odpowiedź, którą chcesz udzielić w tej sondzie!");
            return false;
        }
        return true;
    });
    
    $("#mailThisPageForm").submit(function(){
        if (!/^[a-zA-Z0-9\-_\.]+?@[a-zA-Z0-9\-_\.]+?\.[a-zA-Z]{2,4}$/.test($("#mail_this_od").val()))
        {
            alert("Podaj swój adres e-mail!");
            $("#mail_this_od").focus();
            return false;
        }
        if (!/^[a-zA-Z0-9\-_\.]+?@[a-zA-Z0-9\-_\.]+?\.[a-zA-Z]{2,4}$/.test($("#mail_this_do").val()))
        {
            alert("Podaj adres e-mail osoby, do której chcesz przesłać wiadomość!");
            $("#mail_this_do").focus();
            return false;
        }
        return true;
    });
    
    $("#commentForm").submit(function(){
       if($("#comment").val().length==0 || $("#comment").val()=="Tutaj wpisz swój komentarz...")
        {
            alert("Wpisz treść komentarza, który chcesz dodać!");
            $("#comment").focus();
            return false;
        }
       return true; 
    });
    
    $("#forumAddTopicForm").submit(function(){
       if($("#forum_temat").val().length==0)
        {
            alert("Wpisz temat wątku, który chcesz rozpocząć!");
            $("#forum_temat").focus();
            return false;
        }
        
       if($("#forum_tresc").val().length==0 || $("#forum_tresc").val()=="Tutaj wpisz swój komentarz...")
        {
            alert("Wpisz treść wiadomości, którą chcesz dodać!");
            $("#forum_tresc").focus();
            return false;
        }
       return true; 
    });
    
    $("#forumAddReplyForm").submit(function(){
       if($("#forum_tresc").val().length==0 || $("#forum_tresc").val()=="Tutaj wpisz swój komentarz...")
        {
            alert("Wpisz treść wiadomości, którą chcesz dodać!");
            $("#forum_tresc").focus();
            return false;
        }
       return true; 
    });
	
	$("#forumEditForm").submit(function(){
       if($("#forum_tresc").val().length==0)
        {
            alert("Wpisz treść wiadomości, którą chcesz zaktualizować!");
            $("#forum_tresc").focus();
            return false;
        }
       return true; 
    });
    
    $('a.galleryRate').rating({ 
        callback: function(val){
            $.ajax({
                type: this.form.method,
                url: this.form.action,
                data: $(this.form).serializeArray(),
                dataType: "html",
                success: function(r) {
                    var txt = (r==1) ? 'Dziękujemy, Twój głos został zapisany!' : 'Twój głos został już zapisany! Możesz głosować tylko jeden raz!';
                    $('input',this.form).rating('disable');
                    $('#ratingConfirm').html(txt)
                },
                error: function(){ alert("Serwer nie odpowiada, odśwież stronę i spróbuj ponownie!") }
            });
        }
    });
    
    $('input.galleryRate').rating({ 
        callback: function(val){
            $.ajax({
                type: this.form.method,
                url: this.form.action,
                data: $(this.form).serializeArray(),
                dataType: "html",
                success: function(r) {
                    var txt = (r==1) ? 'Dziękujemy, Twój głos został zapisany!' : 'Twój głos został już zapisany! Możesz głosować tylko jeden raz!';
                    $('input',this.form).rating('disable');
                    $('#ratingConfirm').html(txt)
                },
                error: function(){ alert("Serwer nie odpowiada, odśwież stronę i spróbuj ponownie!") }
            });
        }
    });
    
    $('#linkToLoginBox').click(function(){
        $.scrollTo('#profil', 800, {onAfter:function(){
            $('#box_authorize_login').focus();
        }});
        return false;
    });
    
    $('.booking').click(function()
    {
        window.open("/rezerwacja.html", "bookingDisplay", "width=960,height=600,toolbar=0,locationbar=1,directories=0,status=1,menubar=0,scrollbars=1,resizable=1,copyhistory=0");
        return false;
    });
    
    
    $('ul#cardMenu li a').click(function()
    {
      if( $(this).parent().hasClass("redir") )
      {
        return true;
      }
        if(MENU_TAB_ID==""){
            $('ul#cardMenu li').each(function(){
                if($(this).hasClass('selected')){
                    MENU_TAB_ID=$(this).attr("id");
                }
            });
        }
        var id = $(this).parent().attr("id");
        if (MENU_TAB_ID!=id)
        {
            $('#'+id+'_content').show();
            $('#'+MENU_TAB_ID+'_content').hide();
            
            $('#'+id).addClass('selected');
            $('#'+MENU_TAB_ID).removeClass('selected');
            
            MENU_TAB_ID=id;
        }
        return false;
    });
    
    
    $('.cartDropItem').click(function(){
        if(confirm("Usunąć produkt?"))
        {
            return true;
        }
        return false;
    });
    
    $('.pmDropItem').click(function(){
        if(confirm("Usunąć wiadomość?"))
        {
            return true;
        }
        return false;
    });
    
    
    
    

    
    /*$('#StronaPolec').click(function()
    {
        alert( this.href )
        return false;
    });*/
    
    
    /*
    $(function() {
        var contactBoxy = null;
        $('#StronaPolec______').click(function()
        {
            contactBoxy=new Boxy.load(this.href+";method=ajax",
                {
                    title: 'Poleć stronę znajomemu',
                    clickToFront : true,
                    cache: true,
                    modal: true,
                    
                    behaviours: function(c) {
                        c.find('#mailThisPageForm').submit(function() {
                            Boxy.get(this).setContent("<div style=\"width: 300px; height: 300px\">Sending...</div>");
                            // submit form by ajax using post and send 3 values: subject, your_email, comment
                            $.post(this.action, $(this).serializeArray(),
                            function(data){
                                //contactBoxy.setContent("<div style=\"width: 300px; height: 300px\">"+data+"</div>");
                                $.setContent("<div style=\"width: 300px; height: 300px\">"+data+"</div>");
                            });
                            return false;
                        });
                    }
                });
              return false;
            });
        });
    */
    
    
    $('.fiszki-wide .outer').accordion({
		header: '.naglowek',
		selectedClass: 'rozwin',
        event: 'click',
		autoHeight: false
	});
    
    
	$('.fiszki .inner').accordion({
		header: '.naglowek',
		selectedClass: 'rozwin',
		//event: 'mouseover',
        event: 'click',
		autoHeight: false
	});

    
    
    $('a[@rel*=lightbox]').fancybox();
    
    
    
    $("#partnerzy").jMyCarousel({
        visible: '100%',
        auto: true,
        speed: 1000,
        circular: true
    });
    
    
    
    $("input.date").mask("99-99-9999");
    $("input.postCode").mask("99-999");
    
	
	$(".partyPanelBoxLink").click(function(){
        $("#partyPanelBox").slideToggle("medium");
        if(this.type!="reset"){return false;}
    });
	$(".partyForm").submit(function(){
        var id = (this.name=="box") ? "#box_" : "#";
        if($(id+"party_imie").val().length==0)
        {
            alert("Podaj swoje imię!");
            $(id+"party_imie").focus();
            return false;
        }
        if($(id+"party_nazwisko").val().length==0)
        {
            alert("Podaj swoje nazwisko!");
            $(id+"party_nazwisko").focus();
            return false;
        }
        if($(id+"party_data_urodzenia").val().length==0)
        {
            alert("Podaj datę urodzenia!");
            $(id+"party_data_urodzenia").focus();
            return false;
        }
        if($(id+"party_data").val().length==0)
        {
            alert("Podaj datę imprezy!");
            $(id+"party_data").focus();
            return false;
        }
        if($(id+"party_guests").val().length==0)
        {
            alert("Podaj liczbę gości!");
            $(id+"party_guests").focus();
            return false;
        }
        if (!/^[a-zA-Z0-9\-_\.]+?@[a-zA-Z0-9\-_\.]+?\.[a-zA-Z]{2,4}$/.test($(id+"party_email").val()))
        {
            alert("Podaj swój adres e-mail!");
            $(id+"party_email").focus();
            return false;
        }
        if($(id+"party_phone").val().length==0)
        {
            alert("Podaj telefon kontaktowy!");
            $(id+"party_phone").focus();
            return false;
        }
        return true;
    });
    
    
    $(".newsletterPanelBoxLink").click(function(){
        $("#newsletterPanelBox").slideToggle("medium");
        if(this.type!="reset"){return false;}
    });
	$(".newsletterForm").submit(function(){
        var id = (this.name=="box") ? "#box_" : "#";
        if($(id+"newsletter_imie").val().length==0)
        {
            alert("Podaj swoje imię!");
            $(id+"newsletter_imie").focus();
            return false;
        }
        if (!/^[a-zA-Z0-9\-_\.]+?@[a-zA-Z0-9\-_\.]+?\.[a-zA-Z]{2,4}$/.test($(id+"newsletter_email").val()))
        {
            alert("Podaj swój adres e-mail!");
            $(id+"newsletter_email").focus();
            return false;
        }
        return true;
    });
    
    
    
    $(".box .header").mouseover(function()
	{
      if ($(this).children(".toggle").length)
      {
        //$(this).children(".toggle").show();
        $(this).children(".toggle").addClass("hover");
      }
	});
	$(".box .header").mouseout(function()
	{
	  if ($(this).children(".toggle").length)
      {
        //$(this).children(".toggle").hide();
        $(this).children(".toggle").removeClass("hover");
      }
	});
    
    
	calendarTip();
	
	$('.box .toggle').click(function()
    {
      $(this).removeClass("down");
      $(this).removeClass("up");
      
      var _parent_id = $(this).parent().parent().attr("id");
      
      var modules = $.cookie('toggle');
      
      if (modules != null)
          modules = $.cookie('toggle').split(",");
      else
          modules = [];
      
      
      if ($(this).parent().next().css("display")=="none" )
      {
        $(this).parent().next("div").slideDown(500);
        $(this).addClass("up");
        $(this).parent().next().next().removeClass("footer_toggle");
        
        modules = jQuery.grep(modules, function(v){
          return v!=_parent_id;
        });
      }
      else
      {
        $(this).parent().next("div").slideUp(500);
        $(this).addClass("down");
        
        $(this).parent().next().next().addClass("footer_toggle");
        
        modules.push(_parent_id)
      }
      
      var _set = (modules.length>0) ? String(modules) : null;
      $.cookie('toggle', _set, { expires: 7, path: "/" });
      
      return false;
	});
	
    
    
	
	
	
	
	
	
	
	$('.forum .toggle').click(function()
    {
      $(this).removeClass("down");
      $(this).removeClass("up");
      
      var _parent_id = $(this).parent().attr("id")
	  
      var modules = $.cookie('toggleForum');
	  
      
	  if (modules != null)
          modules = $.cookie('toggleForum').split(",");
      else
          modules = [];
      
      
      if ($(this).parent().next().css("display")=="none" )
      {
        $(this).parent().next("table").slideDown(500);
        //$(this).addClass("up");
        //$(this).parent().next().next().removeClass("footer_toggle");
		
		$(this).parent().removeClass("collapsed");
		
        modules = jQuery.grep(modules, function(v){
          return v!=_parent_id;
        });
      }
      else
      {
        $(this).parent().next("table").slideUp(500);
        //$(this).addClass("down");
        //$(this).parent().next().next().addClass("footer_toggle");
		
		$(this).parent().addClass("collapsed");
		
        
        modules.push(_parent_id)
      }
      
      var _set = (modules.length>0) ? String(modules) : null;
      $.cookie('toggleForum', _set, { expires: 7, path: "/" });
      
      return false;
	});
    
    
    
	
	$('.move').sortable({
      items: '> .box',
      handle: 'h1',
      cursor: 'move',
      containment: 'parent',
      axis: 'y',
      scroll: true,
      scrollSensitivity: 100,
      scrollSpeed: 5,
      revert: true,
      tolerance: 'pointer',
      placeholder: 'drag_pattern',
      dropOnEmpty: true,
      start: function(e,ui) {
        ui.helper.addClass('holder').prepend('<div class="top"></div><div class="bottom"></div>');
      },
      update: function() {
        var modules = $.cookie('modules');
        
        if (modules != null)
            var modules = $.cookie('modules').split(",");
        
        var _this_container = String($(this).sortable('toArray')).split(",");
        var _rest_container = '';
        
        if (modules != null)
        {
            for (i = 0; i < modules.length; i++)
            {
                if (!_this_container.inArray(modules[i]))
                    _rest_container += modules[i] + ',';
            }
        }
        _this_container = $(this).sortable('toArray');
        
        $.cookie('modules', String(_rest_container) + String(_this_container), { expires: 7, path: "/" });
      }
	});
});
