$(document).ready(function(){
  
  // handle the property table height
  $('div.property').each(function(){
    var $this = $(this);
    var tableHeight = $this.find('table').height();
    var imageHeight = $this.find('img').height() + 55;
    
    while(tableHeight >= imageHeight)
    {
      tableHeight = $this.find('table').height();
      
      $this.find('table tr:last').remove();
      $this.find('table tr:last td').addClass('no_border');
    }
  });
  
  // cache selectors
  var $modalCloseButton = $('#cboxClose');
  var $slovakMapSwitch = $('#map_sk');
  var $czechMapSwitch = $('#map_cz');
  var $slovakMap = $('div#map_switch .map_sk');
  var $czechMap = $('div#map_switch .map_cz');
  var $textblokTable = $('div.textblok table');

  // ajax loader
  $('div#ajax_loading').bind('ajaxSend', function(){
    $(this).show();
  }).bind('ajaxComplete', function(){
    $(this).hide();
  });
  
  // style last tr and drop shadow
  $textblokTable.each(function(){
    $(this).find('tr:last').css({'border-bottom':'1px solid #FFFFFF'});
  }).after('<div class="table_shadow">&nbsp;</div>');

  // style tables hover
  $textblokTable.delegate('tr','mouseover mouseout',function(e){
    $(this).find('td').css({'background':'#f0f5f8'});
    
      if(e.type === 'mouseover')
      {
        $(this).find('td').css({'background':'#f0f5f8'});
      }
      else if(e.type === 'mouseout')
      {
        $(this).find('td').css({'background':'#f2f1ee'});
      }
  });
  
  // init lightbox
  $('a[rel=lbox]').lightBox({
    txtImage: __('lb_image'),
    txtOf: __('lb_image_of')
  });
  
  // init scrollable
  $('.scrollable').scrollable();

  // fire image cycle
  $('div#image_cycle').imagecycle({
    speed: 800,
    firedspeed: 500,
  	interval: 5000,
    paused: false,
    textclass: 'div.image_cycle_content',
    textparent: 'div#image_cycle_back'
  });
  
  // init colorbox
  $('#feeedback').colorbox({
    inline: true, 
    href:'#feedback_block',
    width: '554px',
    scrolling: false,
    overlayClose: false,
    onLoad: function(){
      $modalCloseButton.hide();
    },
    onComplete: function(){
      $modalCloseButton.show();
    },
    onOpen: function(){
      $('body,html').css({'overflow':'hidden'});
    },
    onClosed: function(){
      $('body,html').css({'overflow':'auto'});
    }
  });
  
  /*
    BEGIN DOM STUFF
  */
  
  // property mail form show
  $('#send_property_mail').click(function(){
    $('#send_property_mail_holder').slideToggle(400);
  });
  
  // simple blinking function
  $.fn.blink = function(times,speed){
    return this.each(function(){
      var $this = $(this);
      
      for(var i=0;i<times;i++)
      {
        $this.fadeOut(speed).fadeIn(speed);
      }
    });
  };
  
  // fix img position
  $('div.partner_node img').each(function(){
    $(this).css({
      'margin-top': -($(this).height()/2) + 'px'
    });
  });

  // different language stuff
  
  switch(_LANG)
  {
    // slovak
    case 'sk': {
      $modalCloseButton.css({'background':'url(' + _BASE + 'images/close_sk.jpg) 0px 0px no-repeat'});
    } break;
    
    // czech
    case 'cz': {
      $modalCloseButton.css({'background':'url(' + _BASE + 'images/close_cz.jpg) 0px 0px no-repeat'});
    } break;
    
    // english
    case 'en': {
      $modalCloseButton.css({'background':'url(' + _BASE + 'images/close_en.jpg) 0px 0px no-repeat'});
    } break;
    
    // fallback to slovak
    default: {
      $modalCloseButton.css({'background':'url(' + _BASE + 'images/close_sk.jpg) 0px 0px no-repeat'});
    } break;
  }
  
  // check for native css3 border radius support
  var style = document.createElement('div').style;
  var moz = style['MozBorderRadius'] !== undefined;
  var webkit = style['WebkitBorderRadius'] !== undefined;
  var radius = style['borderRadius'] !== undefined || style['BorderRadius'] !== undefined;
  
  // only apply if necessary
  if(!moz && !webkit && !radius)
  {
    $('div#header div#menu_area div#menu ul li ul li a').corner('3px');
  }
  
  // ie6 fixing for hover
  if($.browser.msie && $.browser.version === '6.0')
  {
    $('div#header div#menu_area div#menu ul li ul li').delegate('a','mouseover mouseout',function(e){
      if(e.type === 'mouseover')
      {
        $(this).css({
          'background': '#374e5e',
          'color': '#FFFFFF'
        });
      }
      else if(e.type === 'mouseout')
      {
        $(this).css({
          'background': 'transparent',
          'color': '#6b685e'
        });
      }
    });
  }
  
  // newsletter click erase your email text
  $('#newsletter_value').click(function(){
    var $this = $(this);
    var value = $this.val();
    
    // check for all languages
    if(value === 'Váš e-mail ...' || value === 'Your e-mail ...')
    {
      $this.val('');
    } 
  }).blur(function(){
    var $this = $(this);
    var value = (_LANG === 'en') ? 'Your e-mail ...' : 'Váš e-mail ...';
    
    // replace blank value with default message
    if($.trim($this.val()) === '')
    {
      $this.val(value);
    }
  });
  
  // contact map switchers
  $slovakMapSwitch.click(function(){
    $slovakMapSwitch.parent('li').addClass('active_switch');
    $czechMapSwitch.parent('li').removeClass('active_switch');
    
    if($slovakMap.is(':hidden'))
    {
      $czechMap.fadeOut(200,function(){
        $slovakMap.fadeIn(200);
      });
    }
  });
  
  $czechMapSwitch.click(function(){
    $czechMapSwitch.parent('li').addClass('active_switch');
    $slovakMapSwitch.parent('li').removeClass('active_switch');
    
    if($czechMap.is(':hidden'))
    {
      $slovakMap.fadeOut(200,function(){
        $czechMap.fadeIn(200);
      });
    }
  });
  
  /*
    PROPERTY
    SEARCH
  */
  $('li.cz_setting,li.sk_setting').click(function(){
    var $this = $(this);
    var $searchRepublic = $('#search_republic');
    
    if($this.css('text-decoration') === 'none')
    {
      $this.css({'text-decoration':'underline'});
    }
    else
    {
      $this.css({'text-decoration':'none'});
    }
    
    var isCz = ($('li.cz_setting').css('text-decoration') === 'underline');
    var isSk = ($('li.sk_setting').css('text-decoration') === 'underline');
    var isBoth = isCz && isBoth;
    
    if(isBoth)
    {
      $searchRepublic.val('both');
    }
    else if(isCz && !isSk)
    {
      $searchRepublic.val('cz');
    }
    else if(isSk && !isCz)
    {
      $searchRepublic.val('sk');
    }
    else
    {
      $searchRepublic.val('both');
    }
    
    $('div#property_search form').submit();
  });
  
  $('#search_section').change(function(){
    var value = $(this).val();
    var isCz = (($('li.cz_setting').css('text-decoration') === 'underline') ? 'yes' : 'no');
    var isSk = (($('li.sk_setting').css('text-decoration') === 'underline') ? 'yes' : 'no');
    var lang_setting = isSk + '|' + isCz;

    $('#property_search_inner').load(_BASE + 'ajax/generate_search',{ 
      value: value, 
      lang: _LANG, 
      lang_setting: lang_setting 
    });
  });
  
  /*
    BEGIN AJAX STUFF
  */
  
  // submit newsletter
  $('#newsletter_submit').click(function(){
    var data = { 
      email: $('#newsletter_value').val() 
    };
    
    if(!__email(data.email))
    {
      jAlert(__('invalid_email'),__('filling_error'));
      return false;
    }
    
    $.post(_BASE + 'ajax/add_newsletter',data,function(json){
      var response = '';
      
      switch(json.msg)
      {
        case 'FALSE': {
          response = __('newsletter_false');
        } break;
        case 'INVALID_EMAIL': {
          response = __('invalid_email');
        } break;
        case 'EMAIL_EXISTS': {
          response = __('newsletter_email_exists');
        } break;
        case 'INSERT_ERROR': {
          response = __('newsletter_false');
        } break;
        case 'TRUE': {
          response = __('newsletter_true');
          $('#newsletter_value').val(__('newsletter_default'));
        } break;
        default: {
          response = __('newsletter_false');
        } break;
      }
      
      jAlert(response,__('newsletter'));
    },'json');
  });
  
  // send feedback
  $('#send_feedback').click(function(){
    var $feedbackEmail = $('#feedback_email');
    var $feedbackComment = $('#feedback_comment');
    var data = { 
      email: $feedbackEmail.val(),
      comment: $feedbackComment.val()
    };
    
    if(!__email(data.email))
    {
      $feedbackEmail.blink(3,150);
      return false;
    }
    
    if($.trim(data.comment) === '')
    {
      $feedbackComment.blink(3,150);
      return false;
    }
    
    $.post(_BASE + 'ajax/send_feedback',data,function(json){
      var response = '';
      
      switch(json.msg)
      {
        case 'FALSE': {
          response = __('feedback_false');
        } break;
        case 'INVALID_EMAIL': {
          response = __('invalid_email');
        } break;
        case 'NO_MESSAGE': {
          response = __('feedback_no_msg');
        } break;
        case 'TRUE': {
          response = __('feedback_true');
        } break;
        default: {
          response = __('feedback_false');
        } break;
      }
      
      jAlert(response,__('feedback'),function(){
        if(response === __('feedback_true'))
        {
          window.location.reload();
        }
      });
    },'json');
  });
  
  // send property email
  $('#send_property_mail_submit').click(function(){
    var $propertyEmail = $('#send_property_mail_val');

    var data = {
      email: $propertyEmail.val(),
      link: window.location.href
    };
    
    if(!__email(data.email))
    {
      jAlert(__('invalid_email'),__('email_property_form'));
      return false;
    }
    
    $.post(_BASE + 'ajax/send_property_email',data,function(json){
      var response = '';
      
      switch(json.msg)
      {
        case 'FALSE': {
          response = __('property_form_false');
        } break;
        case 'INVALID_EMAIL': {
          response = __('invalid_email');
        } break;
        case 'TRUE': {
          response = __('property_form_true');
        } break;
        default: {
          response = __('property_form_false');
        } break;
      }
      
      jAlert(response,__('email_property_form'),function(){
        if(response === __('property_form_true'))
        {
          window.location.reload();
        }
      });
    },'json');
  });
  
  // send contanct form
  $('#contact_form_submit').click(function(){
    var $contactFormName = $('#contact_form_name');
    var $contactFormPhone = $('#contact_form_phone');
    var $contactFormEmail = $('#contact_form_email');
    var $contactFormText = $('#contact_form_text');
    var errors = [];
    var data = { 
      name: $contactFormName.val(),
      phone: $contactFormPhone.val(),
      email: $contactFormEmail.val(),
      text: $contactFormText.val()
    };

    if($.trim(data.name) === '')
    {
      errors.push(__('no_name'));
    }
    
    if($.trim(data.phone) === '')
    {
      errors.push(__('no_phone'));
    }
    
    if(!__email(data.email))
    {
      errors.push(__('invalid_email'));
    }
    
    if($.trim(data.text) === '')
    {
      errors.push(__('no_message'));
    }

    if(errors.length)
    {
      jAlert(__format(errors),__('filling_error'));
    }
    else
    {
      $.post(_BASE + 'ajax/send_contact_form',data,function(json){
        var response = '';
        
        switch(json.msg)
        {
          case 'FALSE': {
            response = __('contact_form_false');
          } break;
          case 'INVALID_EMAIL': {
            response = __('invalid_email');
          } break;
          case 'NO_NAME': {
            response = __('contact_form_no_name');
          } break;
          case 'NO_PHONE': {
            response = __('contact_form_no_phone');
          } break;
          case 'NO_MESSAGE': {
            response = __('no_message');
          } break;
          case 'TRUE': {
            response = __('contact_form_true');
          } break;
          default: {
            response = __('contact_form_false');
          } break;
        }
        
        jAlert(response,__('contact_form'),function(){
          if(response === __('contact_form_true'))
          {
            window.location.reload();
          }
        });
      },'json');
    }
  });
});

/*
  BASIC
  JS FUNCTIONS
*/

// wrotes pagination
function page_wrotes(page)
{
  $('div#wrote_about_us').load(_BASE + 'ajax/wrote_paging/' + page);
}
