$(document).ready(function() {
  
  $(".box-green-header-extend").click(function(){
    var url = $(this).prev('.box-green-header-list-item-container').find('a').attr("href");
    window.location = url;
  })
  
  $("#newsletter-box input, #newsletter-quick-box input").each(function(){
    label = $(this).parent().find('label').hide();
    text = label.text();
    label.next().val(text);
  });
  $("#newsletter-box input, #newsletter-quick-box input").focus(function(){
    label = $(this).parent().find('label');
    text = label.text();
    if($(this).val() == text) {
      $(this).val('');
    }
  });
  $("#newsletter-box input, #newsletter-quick-box input").blur(function(){
    label = $(this).parent().find('label');
    text = label.text();
    if($(this).val() == '') {
      $(this).val(text);
    }
  });

  $('ul#search-tabs li.noclegi').click(function() {
    $("#wycieczki").hide();
    $("#noclegi").show();
    $("#search-block-front").addClass('noclegi');
  });
  $('ul#search-tabs li.wycieczki').click(function() {
    $("#noclegi").hide();
    $("#wycieczki").show();
    $("#search-block-front").removeClass('noclegi');
  });
  
  $('a.select-all').click(function() {
    $(this).parent().parent().parent().find('input[type=checkbox]').attr("checked","checked");
    return false;
  });
    
  $('a.deselect-all').click(function() {
    $(this).parent().parent().parent().find('input[type=checkbox]').attr("checked","");
    return false;
  });
 
  $('li.destination input[type=text]').click(function(){
    $("#destination .columns input, #departures .columns input").each(function(){
      $(this).attr("disabled",false);
    })
    $('.layer').hide();
    $("#destination").css('top',$(window).scrollTop()+20);
    
    
    
    if($("#wrapper").hasClass('page-front')){
      var left = -40;
      $("#destination").css("left",left);
    }
    else{
      var left = $(window).width() - $("#destination").width();
      left = left/2
      if(left>0) $("#destination").css("left",left);
    }
    $('#destination').show();
    var width = 5;
    $("#destination .col").each(function(){
      width += $(this).width();
    });
    $("#destination").width(width);
  });
  
  $('li.wyjazdz input[type=text]').click(function(){
    $("#destination .columns input, #departures .columns input").each(function(){
      $(this).attr("disabled",false);
    })
    $('.layer').hide();
    
    
    
    $("#departures").css('top',$(window).scrollTop()+20);
    if($("#wrapper").hasClass('page-front')){
      var left = 20;
      $("#departures").addClass('wyjazdz-front');
    }
    else{
      var left = $(window).width() - $("#destination").width();
      left = left/2
    }
    if(left>0) $("#departures").css("left",left);
    $('#departures').show();
    var width = 5;
    $("#departures .col").each(function(){
      width += $(this).width();
    });
    $("#departures").width(width);
  });
  
  
  $("#closeDestinations").click(function(){
    var checked = $('li.destination input[type=text]').val().split(', ');
    $("#destination input[type=checkbox]").each(function(){
      if(checked.has($(this).parent().next('label').html())!==false){
        $(this).attr("checked","checked");
      }
      else{
        $(this).attr("checked","");
      }
    });
    $("#destination").hide();
    return false;
  })
  
  $("#more-departures a").click(function() {
    $("#departures").css('top',$(window).scrollTop()+20);
    var left = $(window).width() - $("#departures").width();
    left = left/2
    $("#departures").css("left",(left>0)?left:"0");
    $("#departures").show();    
    return false;
  });
  
  
  if($("#departures input:checked").length==0){
    $('li.wyjazdz input[type=text]').val('dowolny');
  }
  
  if($("#destination input:checked").length==0){
    $('li.destination input[type=text]').val('wybierz kierunkiiii');
  }
  $("#hideDepartures").click(function() {    
    generateDepartures();
    return false;
  });
  
  $("#closeDepartures").click(function() {
    var checked = $('li.wyjazdz input[type=text]').val().split(', ');
    $("#departures input[type=checkbox]").each(function(){
      if(checked.has($(this).parent().next('label').html())!==false){
        $(this).attr("checked","checked");
      }
      else{
        $(this).attr("checked","");
      }
    });
    $("#departures").hide();    
    return false;
  });
  
  generateDepartures();
  generateDestinations();
  $("#hideDestinations").click(function(){
    generateDestinations();
    return false;
  });
 
  $('#no-passport').change(function(){
    var checked = $(this).attr("checked");
    selectGroup(checked,'#destination','noPassport');
    $(this).attr("checked",checked);
  });
  $('#mediterranean').change(function(){
    var checked = $(this).attr("checked");
    selectGroup(checked,'#destination','mediterranean');
    $(this).attr("checked",checked);
  });
  $('#islands').change(function(){
    var checked = $(this).attr("checked");
    selectGroup(checked,'#destination','islands');
    $(this).attr("checked",checked);
  });
  $('#exotic').change(function(){
    var checked = $(this).attr("checked");
    selectGroup(checked,'#destination','exotic');
    $(this).attr("checked",checked);
  });
  $('#closeAndWarm').change(function(){
    var checked = $(this).attr("checked");
    selectGroup(checked,'#destination','closeAndWarm');
    $(this).attr("checked",checked);
  });
  $('#skiing').change(function(){
    var checked = $(this).attr("checked");
    selectGroup(checked,'#destination','skiing');
    $(this).attr("checked",checked);
    
  });
  $("#select-all").change(function(){
    var checked = $(this).attr("checked");
    $(this).parent().parent().find('.columns input[type=checkbox]').attr("checked",checked);
    $("#destination .navigation input[type=checkbox]").each(function(){
      $(this).attr("checked", false);
    });
    $(this).attr("checked",checked);
  });
  
  $("#deselect-all").change(function(){
    $(this).parent().parent().parent().find('input[type=checkbox]').attr("checked",false);
    //    $("#destination .navigation input[type=checkbox]").each(function(){
    //      $(this).attr("checked", false);
    //    });
    $(this).attr("checked",true);
  });
  
  $('#search-criteria a.organizator-show').click(function(){
    $('#search-criteria div.organizator').slideDown();
    $('#search-criteria a.organizator-hide').show();
    $(this).prev('h3').css('background-image', 'url(../images/white-right-blue-arrow.png)');
    $(this).hide();
    return false;
  });
    
  $('#search-criteria a.organizator-hide').click(function() {
    $('#search-criteria div.organizator').slideUp();
    $('#search-criteria a.organizator-show').show();
    $(this).hide();
    $("#search-criteria .label h3").css('background-image', 'url(../images/white-down-blue-arrow.png)');
    return false;
  });
  
  $('.childs').each(function(){
    prepare_childs_age(this);
  })
  $('.childs').live('change',function(){
    prepare_childs_age(this);
  });
  
  $('#rooms').each(function(){
    prepare_rooms();
  })
  $('#rooms').change(function(){
    prepare_rooms();
  });
  
  $('#destination li.parent input[type=checkbox]').click (function(){
    var thisCheck = $(this);
    var label = thisCheck.parent().next('label').html();
    
    var classes = thisCheck.parent().parent().attr('class');
    classes = classes.split(' ');
    var id = classes[1].substr(7);
    var parent = findparent(thisCheck,'.columns');
    parent.find('li.region-'+id+' input[type=checkbox]').each(function(){
      if (thisCheck.is(':checked')){
        $(this).attr('checked','checked');
      }
      else{
        $(this).attr('checked','');
      }
    });
  });
  
  addMore('#touroperators-criteria', 10, 'li',"Pokaż wszystkie","Ukryj");
  addMore('#left .departures',5, 'li',"Pokaż","Ukryj");
  addMore('.listDescriptionBox table', 5, 'tr',"Pokaż wszystkie","Ukryj")
  
  $('.trip-question INPUT.text, .trip-question TEXTAREA').each(function(){
    var label = $(this).prev('label').hide().html();
    $(this).val(label);
  });
  $('.trip-question INPUT.text, .trip-question TEXTAREA').click(function(){
    var label = $(this).prev('label').html();
    if(label == $(this).val()){
      $(this).val('');
    }
  });
  $('.trip-question INPUT.text, .trip-question TEXTAREA').blur(function(){
    if($(this).val()==''){
      var label = $(this).prev('label').html();
      $(this).val(label);
    }
  });
  
  $('.TripDetails_Button .askform A').click(function(){
    $('.tripquestion').show();
    return false;
  });
  
  $('.trip-question .cancel').click(function(){
    $('.tripquestion').hide();
    return false;
  })
  
  $('.change').click(function(){
    $("#change-content").remove();
    $(this).after('<div id="change-content"></div>');
    $("#change-content").load($(this).attr("href"));
    return false;
  });
  
  $('.change-close').live('click',function(){
    $("#change-content").remove();
    return false;
  });
  
  $('.submit').live('click',function(){
    var form = findparent($(this), 'form');
    form.submit();
  });
  
  $(".TripDetails_SummaryForm #services li.description").each(function(){
    $(this).hide();
  });
  $(".TripDetails_SummaryForm #services li.description a.hide-desc").click(function(){
    $(this).parent().hide();
    return false;
  });
  
  $(".TripDetails_SummaryForm #services li.header a.show-desc").click(function(){
    $(this).parent().next('.description').show();
    return false;
  });
  
  $('a.thumbnails').each(function(){
    $(this).append('<img class="lens" src="/images/icons/lens.png" />');
  })
  
  $("#services input[type=checkbox]").change(function(){
    if($(this).hasClass('excludes')){
      var classes = $(this).attr('class').split(' ');
      for(i in classes){
        if(typeof(classes[i]) == 'string' && classes[i].indexOf('exclude-')>=0){
          var id = classes[i].substr(8);
          id--;
          $("#add_service_"+id+"_number").attr("checked",false);
          $("#add_service_"+id+"_number").attr("disabled",$(this).attr('checked'));
        }
      }
    }
  //add_service_9_number
  });
  
  $(".close-loginbox").click(function(){
    $("#login-form form").hide();
    $(".close-loginbox").hide();
    return false;
  })
  
  $("#zaloguj-sie a").click(function(){
    $("#login-form form").show();
    $(".close-loginbox").show();
    return false;
  });
  
  $("input.copy").blur(function(){
    var classes = $(this).attr('class').split(' ');
    for(i in classes){
      if(typeof(classes[i]) == 'string' && classes[i].indexOf('copy-')>=0){
        var copyclass = classes[i].substr(5);
        $('div.sameaddress .'+copyclass).val($(this).val());
      }
    }
  });
  
  $('input.sameaddress').change(function(){
    if($(this).attr("checked")){
      findparent($(this), ".subsection").addClass('sameaddress').find('.copyhide').parent().hide();
    //$('.copyhide').parent().hide();
    }
    else{
      findparent($(this), ".subsection").removeClass('sameaddress').find('.copyhide').parent().show();
    //$('.copyhide').parent().show();
    }
  });
  
  $('.copyhide').each(function(){
    $(this).parent().hide();
  });
  
  $('.refreshPrice').click(function(){
    refreshTotalPrice($(this));
    return false;
  });
  
  $('a.show-details').toggle(
    function(){
      findparent($(this),'tr').next('tr').show();
      $(this).html('ukryj szczegóły');
      return false;
    },
    function(){
      findparent($(this),'tr').next('tr').hide();
      $(this).html('pokaż szczegóły');
      return false;
    }
    );
  $('a.hide-details').click(function(){
    var tr = findparent($(this),'tr');
    tr.hide();
    tr.prev('tr').find('a.show-details').html('pokaż szczegóły');
    return false;
  });
  
  $('.page-oferta-noclegi .price IMG').toggle(
    function(){
      $(this).next('div.price-details').show();
    },
    function(){
      $(this).next('div.price-details').hide();
    }
   );
  
});


var child_prepared = false;

function refreshTotalPrice(obj){
  var params = new Object();
  if(obj){ 
    var classes = obj.attr('class').split(' ');
    //console.log(classes);
    for(i in classes){
      if(typeof(classes[i]) == 'string' && classes[i].indexOf('refresh-')>=0){
        var param = classes[i].substr(8).split('_', 2);
        params[param[0]] = param[1];
      }
    }
  }
  $(".TripDetails_Button .OfferPrice SPAN").load('/totalPrice.jsp', params);
}

function prepare_childs_age(selector){
    
  var childs = 0;
  if(typeof(childrens_age) != "undefined" && !child_prepared){
    child_prepared = true;
    for(i in childrens_age){
      if(childrens_age[i] >= 0){
        childs++;
      }
    }
  }
  if(childs==0){
    var val = $(selector).val();
  }
  else{
    var val = childs;
    $(selector).val(childs);
  }
  //console.log(val);
  
  //console.log("."+$(selector).attr('id')+".wiek-dzieci");
  var childs_age = $("."+$(selector).attr('id')+".wiek-dzieci");
  if(val < 1 ) {
    childs_age.hide();
    return;
  }
  childs_age.show();
  var output = '';

  for(var i=1; i<=val; i++){
    var options = '<option selected="" value="-1">---</option>';
    options += '<option selected="" value="1"><2</option>';
    for(var j=2; j<18; j++){
      var selected = '';
      if(childrens_age[i-1] == j){
        selected = 'selected="selected"';
      }
      options += '<option value="'+j+'" '+selected+'>'+j+'</option>';
    }
    output += '<select name="criterias_child'+i+'" class="criterias-child-'+i+'">'+options+'</select>';
  }
  childs_age.find('.selects').html(output);
     
}

function findparent(haystack,needle){
  newparent = haystack.parent();
  while(true){
    if(newparent.is(needle)) return newparent;
    newparent = newparent.parent();
    if(newparent.length==0) return false;
  }
}

function selectGroup(checked,wrapper,group){
  if(checked){
    $(wrapper+'navigation input[type=checkbox]').each(function(){
      $(this).attr("checked",false);
    });
  
    $(wrapper+' input').each(function(){
      $(this).attr('checked','');
      if($(this).hasClass(group)) $(this).attr('checked','checked');
    });
  }else{
    $(wrapper+' input').each(function(){
      if($(this).hasClass(group)) $(this).attr('checked',false);
    });
  }
}

function addMore(element, count, needle, textShow,textHide){
  var list = $(element);
  var i=0;
  list.find(needle).each(function(){
    i++;
    if(i>=count) $(this).hide();
  });
  if(needle == 'tr'){
    list.append("<tr class=\"toggle-elements\"><td colspan=\"5\"><a class=\"more\" onclick=\"toggleElements("+count+",this,'"+needle+"','"+textShow+"','"+textHide+"'); return false;\" href=\"#\">"+textShow+"</a></td></tr>");
  }else{
    list.append("<"+needle+" class=\"toggle-elements\"><a class=\"more\" onclick=\"toggleElements("+count+",this,'"+needle+"','"+textShow+"','"+textHide+"'); return false;\" href=\"#\">"+textShow+"</a></"+needle+">");
  }
//console.log("<"+needle+" class=\"toggle-elements\"><a class=\"more\" onclick=\"toggleElements("+count+",this,'"+needle+"'); return false;\" href=\"#\">Pokaż wszystkie</a></"+needle+">");
}

function toggleElements(count, element, needle, textShow,textHide){
  var parent = 'ul';
  switch(needle){
    case 'li':
      parent = 'ul';
      break;
    case 'tr':
      parent = 'table';
      break;
  }
  var link = $(element);
  var list = findparent(link, parent);

  if(link.hasClass('more')){
    list.find(needle).each(function(){
      if(!$(this).hasClass('toggle-elements')){
        $(this).show();
      }
    });
    link.removeClass('more');
    link.addClass('less');
    link.html(textHide);
  }
  else{
    var i=0;
    list.find(needle).each(function(){
      if(!$(this).hasClass('toggle-elements')){
        i++;
        if(i>=count) $(this).hide();
      }
    });
    link.removeClass('less');
    link.addClass('more');
    link.html(textShow);
  }

  //$('html,body').scrollTop(list.offset().top)
  return false;
}

function prepare_rooms(){
  var val = $("#rooms").val();
  var parent = $("#rooms").parents('.daty');

  $('.kwatera').each(function(){
    $(this).remove();
  });
    
  var parents_options = '<option selected="" value="-1">---</option>'; 
  for(i=1; i<=6; i++){
    parents_options += '<option value="'+i+'">'+i+'</option>'; 
  }
  
  var childs_options = '<option value="-1" >---</option>';
  for(i=1; i<=4; i++){
    childs_options += '<option value="'+i+'" >'+i+'</option>';
  }
  
  for(j=val; j>0; j--){
    var output = '<li class="kwatera room-'+j+'">'+
    '<div class="room-number">Pokój '+j+'</div>'+
    '<div class="dorosli dorosli-'+j+'">'+
    '<label for="dorosli">'+
    'Dorośli'+
    '</label>'+
    '<select name="dorosli-'+j+'">' +
    parents_options+
    '</select>'+
    '</div>'+
    '<div class="dzieci">'+
    '<label for="childs">'+
    'Dzieci'+
    '</label>'+
    '<select name="childs-'+j+'"  id="dzieci-noclegi-'+j+'" class="childs">'+
    childs_options+
    '</select>'+
    '</div>'+
    '<div class="wiek-dzieci dzieci-noclegi-'+j+'" style="display:none;">'+
    '<label for="">'+
    'Wiek dzieci'+
    '</label>'+
    '<div class="selects">'+
    '</div>'+
    '</div>'+
    '</li>';
    parent.next().after(output);
  }
}

Array.prototype.has=function(v){
  for (i=0;i<this.length;i++){
    if (this[i]==v) return i;
  }
  return false;
}

function generateDestinations(){
  $("#destination").hide();
  var checked = new Array();
  var i = 0;
  $("#destination input:checked").each(function() {
    checked[i] = $(this).parent().next('label').html();
    i++;
  });
    
  if(i>0){
    var text = checked.join(', ');
  }
  else{
    var text = 'wybierz kierunek';
  }
  $('li.destination input[type=text]').val(text);
    

}

function generateDepartures(){
  if($("#wrapper").hasClass('page-front')){
    var checked = new Array();
    var i = 0;
    $("#departures input:checked").each(function() {
      checked[i] = $(this).parent().next('label').html();
      i++;
    });
    if(i>0){
      var text = checked.join(', ');
    }
    else{
      var text = 'dowolny';
    }
    $('li.wyjazdz input[type=text]').val(text);
  }
  else{
    $("#departures input:checked").each(function(){
      var val = $(this).parent().next().html();
      $("#departures-mini input[value='"+val+"']").attr("checked",true);
    });
  }
  $("#departures").hide();
}
