var SITE_URL = 'https://localhost/change_me/';

var new_messages_id = 0;
var new_messages_user_id = 0;
var new_messages_username = '';

function relocate(url) {
  window.location.href = url;
}

function checkEmail(email) {
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  if ( !filter.test(email) ) {
    return false;
  } else {
    return true;
  }
}

function createCookie(name, value, days) {
  var expires = "";
	
  if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires=" + date.toGMTString();
	}

  document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');

	for(var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
      c = c.substring(1,c.length);
    }

		if (c.indexOf(nameEQ) == 0) {
      return c.substring(nameEQ.length,c.length);
    }
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function populate_provinces() {
  var country_code = $('#country').val();
  
  $('#province').removeOption(/./);
  $('#pre_loading').html(LOADING_REGIONS);
  $('#preloader').show();

  $.ajax({
    type: "POST",
    url: "get_states_cities",
    data: "action=get_states&country_code=" + country_code,
    success: function(msg){
      $('#province').html(msg);
      $('#city').html('<option value="">'+ SELECT_CITY +'</option>');
      $('#preloader').hide();
    }
  });
}

function populate_cities() {
  var country_code = $('#country').val();
  var state_code = $('#province').val();
  
  $('#city').removeOption(/./);
  $('#pre_loading').html(LOADING_CITIES);
  $('#preloader').show();
  
  $.ajax({
    type: "POST",
    url: "get_states_cities",
    data: "action=get_cities&country_code=" + country_code + "&state_code=" + state_code,
    success: function(msg){
      $('#city').html(msg);
      $('#preloader').hide();
    }
  });
}

var q_im = true;
var cq = true;

function read_chat_room() {
  $.ajax({
    type: "POST",
    url: "read_chat_room",
    data: "room_id=" + chat_id,
    success: function(msg){
      if ( msg != 'OFFLINE' ) {
        $('#chat_area').html(msg);
        $('#chat_area').css('color', '#000');
        //if ( check_bottom() ) {
         //$('#chat_board').html(string_html + new_value);
        if ( q_im == true ) {
          if ( cq ) {
            var objDiv = document.getElementById("big_t");
            objDiv.scrollTop = objDiv.scrollHeight;
            cq = false;
          } else {
            animate_down();
          }
        }
  //       alert('da');
  //      } else {
  //        alert('nu');
  //      }
    } else {
      $('#general_title').html();

      $('#chat_area').html('<div style="text-align:center; margin-top:70px; font-size:20px;">' + CHAT_USER_OFFLINE + '</div>');
      $('#chat_area').css('color', 'red');

      $('#small_t').hide();
      $('#big_t').show();
      $('#new_message_div').hide();

      $('#general_ad').hide();
      $('#general_chat').show();
    }
    }
  });
}

function load_chat_room_users() {
  on_load();
  
  $.ajax({
    type: "POST",
    url: "chat_room_users",
    data: "room_id=" + chat_id + "&page=" + page,
    success: function(msg){
      on_unload();
      $('#user_area').html(msg);
   }
  });
}

function load_profile(user_id, username) {
  on_load();
  
  $.ajax({
    type: "POST",
    url: "load_user",
    data: "user_id=" + user_id,
    success: function(msg){
      on_unload();
      if ( msg != 'OFFLINE' ) {
        chat_id = parseInt(msg, 10);
        $('#general_title').css('color', 'white');
        $('#general_title').html(CHAT_CONVERSATION_WITH + username);

        clearInterval(c);

        read_chat_room();
        c = setInterval("read_chat_room()", 3000);

        $('#small_t').hide();
        $('#big_t').show();
        $('#new_message_div').show();

        $('#general_ad').hide();
        $('#general_chat').show();

        read_chat_room();

        load_profile_box(user_id);

        $('#new_message').focus();
        
      } else {
        clearInterval(c);
        $('#general_title').css('color', 'white');
        $('#general_title').html(CHAT_CONVERSATION_WITH + username);

        $('#chat_area').html('<div style="text-align:center; margin-top:70px; font-size:20px;">' + CHAT_USER_OFFLINE + '</div>');
        $('#chat_area').css('color', 'red');

        $('#small_t').hide();
        $('#big_t').show();
        $('#new_message_div').hide();

        $('#general_ad').hide();
        $('#general_chat').show();
      }
   }
  });
}

function load_profile_box() {
  on_load();
  
  $.ajax({
    type: "POST",
    url: "load_user_avatar",
    success: function(msg){
      on_unload();
      $('#right_ads').hide();
      $('#profile').html(msg).show();
    }
  });
}

function animate_down() {
  $('#big_t').animate({scrollTop: $('#big_t > #chat_area').outerHeight()}, -2000);
}

function update_profile() {
  var error = false;
  var alert_error = '';
  /*
  if ( trim( $('#description').val() ) == '' ) {
    error = true;
    alert_error += CHAT_ERROR_DESCRIPTION + "\n";
  }
  */
  if ( trim( $('#country').val() ) == '' ) {
    error = true;
    alert_error += CHAT_ERROR_COUNTRY + "\n";
  }

  if ( trim( $('#province').val() ) == '' ) {
    error = true;
    alert_error += CHAT_ERROR_PROVINCE + "\n";
  }
  
  if ( trim( $('#city').val() ) == '' ) {
    error = true;
    alert_error += CHAT_ERROR_CITY + "\n";
  }

  if ( trim( $('#sex').val() ) == '' ) {
    error = true;
    alert_error += CHAT_ERROR_GENDER + "\n";
  }

  if ( trim( $('#age').val() ) == '' ) {
    error = true;
    alert_error += CHAT_ERROR_AGE + "\n";
  }

  if ( !error ) {
    on_load();
    
    $.ajax({
      data: 'action=update&description=' + $('#description').val() + '&country=' + $('#country').val() + '&province=' + $('#province').val() + '&city=' + $('#city').val() + '&age=' + $('#age').val() + '&sex=' + $('#sex').val() + '&avatar=' + $('#avatar_input').val(),
      url: 'update_user',
      type: 'POST',
      dataType: 'html',
      success: function (msg) {
        on_unload();
        alert(CHAT_SUCCESS_UPDATED);
        $('#general_ad').show();
        $('#general_chat').hide();
        page = 1;
        load_chat_room_users();
      }
    });
  } else {
    alert_error = CHAT_ERROR_FOLLOWING + "\n" + alert_error;
    alert(alert_error);
  }
}

function search_contacts() {
  var sex = 2;
  sex = $('#sex').attr('checked') == true ? 0 : sex;
  sex = $('#sex2').attr('checked') == true ? 1 : sex;
  
  var age1 = $('#age_1').val();
  var age2 = $('#age_2').val();
  if ( age1 > age2 ) {
    alert(CHAT_SEARCH_AGE_BETWEEN);
  }
    
  on_load();
  $.ajax({
    type: "POST",
    url: "chat_room_users",
    data: "room_id=" + chat_id + "&page=" + page + '&action=search&username=' + $('#username').val() + '&country=' + $('#country').val() + '&province=' + $('#province').val() + '&city=' + $('#city').val() + '&sex=' + sex + '&age1=' + age1 + '&age2=' + age2,
    success: function(msg){
      on_unload();
      $('#user_area').html(msg);
   }
  });
}

function block_user (block_id) {
  on_load();
  $.ajax({
    type: "POST",
    url: "block_user",
    data: "user_id=" + block_id,
    success: function(msg){
      on_unload();
      if ( msg == '1' ) {
        $('#unblock_user_status').html(CHAT_BLOCK_USER);
      } else {
        $('#unblock_user_status').html(CHAT_UNBLOCK_USER);
      }
   }
  });
}

function send_new_message() {
  if ( trim( $('#new_message').val() ) != '' && $('#new_message').val() != CHAT_WRITE_MESSAGE ) {
    $.ajax({
      data: 'chat_id=' + chat_id + '&message=' + $('#new_message').val(),
      dataType: 'html',
      type: 'POST',
      url: 'new_message',
      success: function (msg) {
        if ( msg == '' ) {
          $('#new_message').val('');
          
          var break_default = false;
          if ( reading_new_message == '1' ) {
            var new_msg_nr = check_new_message_nr();
            if ( new_msg_nr > 0 ) {
              break_default = true;
              $('#new_messages').trigger('click');
            } else {
              reading_new_message = 0;
            }
          }
          
          if ( !break_default ) {
            if ( chat_id > 1 ) {
              $('#profile').html('').hide();
              $('#right_ads').show();

              $('#general_chat').hide();
              $('#general_ad').show();
							
							chat_id = 1;
            }

            if ( chat_id == 1 ) {
             // $('#general_chat').hide();
              //$('#general_ad').show();
            }
          } 

        }
      }
    });
  }
}

function toggle_emoticons() {
  if ( $('#my_emoticons').css('display') == 'block' ) {
    $('#my_emoticons').css('display', 'none');
  } else {
    $('#my_emoticons').css('display', 'block');
  }
}

function add_emoticon(emoticon_text) {
  var old_message = $('#new_message').val();
  old_message = old_message == CHAT_WRITE_MESSAGE ? '' : old_message;
  
  old_message += emoticon_text;
  
  $('#new_message').val(old_message);
  $('#my_emoticons').css('display', 'none');
}

function search_new_message() {
  $.ajax({
      data: 'chat_id=' + chat_id + '&message=' + $('#new_message').val(),
      dataType: 'html',
      type: 'POST',
      url: 'check_new_message',
      success: function (msg) {
        //msg = parseInt(msg, 10);
        
        var bas = msg.split('###');
        new_messages_id = parseInt(bas[1], 10);
        new_messages_user_id = parseInt(bas[3], 10);
        new_messages_username = bas[2];
        bas[0] = parseInt(bas[0], 10);
        
        var page_title = '';
        if ( bas[0] > 0 ) {
          $('#new_messages').css({ 'color' : 'yellow', 'font-weight' : 'bold' }).children().css({ 'color' : 'yellow', 'font-weight' : 'bold' }).html(bas[0]);
          if ( bas[0] == 1 ) {
            page_title = bas[0] + ' New Message';
          } else {
            page_title = bas[0] + ' New Messages';
          }
        } else {
          $('#new_messages').css({ 'color' : 'white', 'font-weight' : 'normal' }).children().css({ 'color' : 'white', 'font-weight' : 'normal' }).html(bas[0]);
          page_title = CHAT_HTML_TITLE + ' | ' + CHAT_SITE_NAME;
        }
        document.title = page_title;
      }
    });
}

function check_new_message_nr() {
  var msg_nr = 0;
  var result = $.ajax({
    data: 'chat_id=' + chat_id + '&message=' + $('#new_message').val(),
    dataType: 'html',
    type: 'POST',
    async: false,
    url: 'check_new_message',
    success: function (msg) {
    }
  }).responseText;
    
  var bas = result.split('###');
  new_messages_id = parseInt(bas[1], 10);
  new_messages_user_id = parseInt(bas[3], 10);
  new_messages_username = bas[2];
  bas[0] = parseInt(bas[0], 10);
  msg_nr = bas[0];
    
  return msg_nr;
}

function logout() {
  var r = confirm(CHAT_CONFIRM_LOGOUT);
  
  if ( r == true ) {
    window.location = 'home?act=logout';
  }
}

function on_load() {
  var width = parseInt( $(window).width(), 10);
  width = ( width - 80 ) / 2;
  width = width + 'px';
  
  $('#general_loading').css({'left' : width, 'display' : 'block'});
}

function on_unload() {
  $('#general_loading').css({'display' : 'none'});
}

function reactive_ad(ad_id) {
  $('#renew_' + ad_id).toggle();
}

function checkText(text) {
  var accepted_chars = "abcdefghijklmnopqrstuvwxyz1234567890_./";
  var ok = 0;
  var result = true;
  var max_t = text.length;
  
  for ( var i = 0; i < max_t; i++ ) {
    if ( stristr( accepted_chars, text[i] ) == "" ) {
      ok = 1;
    }
  }

  if ( ok == 1 ) {
    result = false;
  }

  return result;
}

function stristr (haystack, needle, bool) {
  // Finds first occurrence of a string within another, case insensitive
  //
  // version: 1109.2015
  // discuss at: http://phpjs.org/functions/stristr    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfxied by: Onno Marsman
  // *     example 1: stristr('Kevin van Zonneveld', 'Van');
  // *     returns 1: 'van Zonneveld'
  // *     example 2: stristr('Kevin van Zonneveld', 'VAN', true);    // *     returns 2: 'Kevin '
  var pos = 0;

  haystack += '';
  pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase());
  if (pos == -1) {
    return false;
  } else {
    if (bool) {
      return haystack.substr(0, pos);
    } else {
      return haystack.slice(pos);
    }
  }
}

function load_avatars() {
  $.ajax({
    data: '',
    dataType: 'html',
    type: 'POST',
    url: 'load_avatars',
    success: function (msg) {
      $('.avatars_box').html(msg);
      $('.avatars_box').show();
    }
  });
}

function change_avatar( new_src ) {
  $('#index_avatar').attr('src', new_src);
  $('#avatar_input').val(new_src);
  $('.avatars_box').hide();
}

function available_period( id ) {
  var from = $('#from_year'+id).val() + '-' + $('#from_month'+id).val() + '-' + $('#from_day'+id).val();
  var to = $('#to_year'+id).val() + '-' + $('#to_month'+id).val() + '-' + $('#to_day'+id).val();
  var country = $('#country'+id).val();
  var ad_zone = $('#ad_zone'+id).val();
  $.ajax({
    data: 'from=' + from + '&to=' + to + '&ad_zone=' + ad_zone + '&country=' + country,
    dataType: 'html',
    type: 'POST',
    url: 'available_period',
    success: function (msg) {
      $('#period_text'+id).html(msg);
    }
  });
}
function change_target( id ) {
  var ad_zone = $('#ad_zone'+id).val();
  if ( ad_zone == '1' || ad_zone == '2' || ad_zone == '3' || ad_zone == '4') {
    $('#country').val('0');
    $('#country').attr('disabled','true');
  } else {
    $('#country').removeAttr('disabled');
  }
}
