var SITE_URL = 'http://www.taganidiot.com/';

function getWidth() {
  var x = 0;
  if (self.innerHeight) {
    x = self.innerWidth;
  }
  else if (document.documentElement && document.documentElement.clientHeight) {
    x = document.documentElement.clientWidth;
  }
  else if (document.body) {
    x = document.body.clientWidth;
  }
  return x;
}

function getHeight() {
  var y = 0;
  if (self.innerHeight) {
    y = self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight) {
    y = document.documentElement.clientHeight;
  }
  else if (document.body) {
    y = document.body.clientHeight;
  }
  return y;
}

function relocate(url) {
  window.location = url;
}

function preloading() {
	for ( i = 0; i < preloading.arguments.length; i++ ) {
		my_images[i] = new Image();
		my_images[i].src = preloading.arguments[i];
	}
}

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) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires=" + date.toGMTString();
	} else {
    var expires = "";
  }

  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 delete_user(id) {
  var r = confirm('Are you sure you want to delete this user?');

  if ( r == true ) {
    window.location = 'admin_users.php?action=delete&id=' + id;
  }
}

function change_option(value, action, to_content) {
  if ( action == 1 ) {
    $('#'+ value + 'on').attr('src', 'images/checked.jpg');
    $('#'+ value + 'off').attr('src', 'images/not_checked.jpg');

    $('#' + to_content).val(action);
  } else {
    $('#'+ value + 'off').attr('src', 'images/checked.jpg');
    $('#'+ value + 'on').attr('src', 'images/not_checked.jpg');
    
    $('#' + to_content).val(action);
  }
}

function read_plate(plate_id) {
  var DATA = '';

  var name = 'plate_div';
  var width = 400;
  var height = 520;

  var screen_width = getWidth();
  var screen_height = getHeight();

  var left = parseInt((screen_width - width) / 2);
  var top = parseInt((screen_height - height) / 2);

  var c = document.createElement('div');
  c.id = name;

  DATA = '<div>\n\
            <div align="right" style="padding: 4px;"><a href="javascript: void(0);" onclick="javascript: close_popup();"><img src="images/close_popup.gif" alt="" border="0" /></a></div>\n\
            <div id="popup_content"></div>\n\
          </div>';

  document.body.appendChild(c);
  $('#' + name).attr('class', 'popup_view_plate');
  $('#' + name).css({'position' : 'absolute', 'top' : parseInt(top) + 'px', 'left' : parseInt(left) + 'px'});
  $('#' + name).html(DATA);

  $('#popup_content').html('<div class="preloader" align="center"><div class="preload">Loading....</div><img src="images/39.gif" /></div>');

  $.ajax({
    type: "POST",
    url: "ajax_load_plate.php",
    dataType: "html",
    data: "plate_id=" + plate_id,
    success: function(msg) {
      $('#popup_content').html(msg);
    }
  });
}

function close_popup() {
  var name = 'plate_div';
  
  var d = document.getElementById('body');
  var olddiv = document.getElementById(name);
  d.removeChild(olddiv);
}

$(document).keypress(function (event) {
  if ( event.keyCode == 27 ) {
    var a = document.getElementById("plate_div");
    if ( a != null ) {
      close_popup();
    }
  }
});


$(document).ready(function() {
  $(document).keypress();
});

function post_comment(post_id) {
  //var name = $('#name').val();
  var name = '';
  var email = $('#email').val();
  var comment = $('#comment').val();

  //if ( name != '' ) {
    if ( comment.length > 20 ) {
      $.ajax({
        type: "POST",
        dataType: "html",
        url: "ajax_post_comment.php",
        //data: "plate_id=" + post_id + "&comment=" + comment + "&email=" + email + "&name=" + name,
        data: "plate_id=" + post_id + "&comment=" + comment + "&email=" + email,
        success: function(msg) {
          if ( msg == 1 ) {
            alert('Message succesfully posted');

            //$('#name').attr('disabled', 'true');
            $('#email').attr('disabled', 'true');
            $('#comment').attr('disabled', 'true');

            close_popup();
          } else {
            alert('An error occured. Please try again.');
          }
        }
      });
    } else {
      alert('Comment must have at least 20 chars.');
    }
  //} else {
    //alert('Please add your name.');
  //}
}

function add_new_plate() {
  var DATA = '';

  var name = 'plate_div';
  var width = 400;
  var height = 360;

  var screen_width = getWidth();
  var screen_height = getHeight();

  var left = parseInt((screen_width - width) / 2);
  var top = parseInt((screen_height - height) / 2);

  var c = document.createElement('div');
  c.id = name;

  DATA = '<div>\n\
            <div align="right" style="padding: 4px;"><a href="javascript: void(0);" onclick="javascript: close_popup();"><img src="images/close_popup.gif" alt="" border="0" /></a></div>\n\
            <div id="popup_content"></div>\n\
          </div>';

  document.body.appendChild(c);
  $('#' + name).attr('class', 'popup_view_plate');
  $('#' + name).css({'position' : 'absolute', 'top' : parseInt(top) + 'px', 'left' : parseInt(left) + 'px'});
  $('#plate_div').css('height', '360px');
  $('#' + name).html(DATA);

  $('#popup_content').html('<div class="preloader" style="padding-top: 80px;" align="center"><div class="preload">Loading....</div><img src="images/39.gif" /></div>');

  var state_val = $('#enter_state').val() == 'Enter state..' ? '' : $('#enter_state').val();

  $.ajax({
    type: "POST",
    url: "ajax_new_plate.php",
    dataType: "html",
    data: "estate=" + state_val,
    success: function(msg) {
      $('#popup_content').html(msg);

      var new_val = $('#enter_plate').val() == 'License plate number...' ? '' : $('#enter_plate').val();
      $('#plate').val(new_val);
    }
  });
}

function post_plate() {
  var state = $('#choose_state').val();
  var plate = $('#plate').val();
  //var subject = $('#subject').val();
  var info = $('#info').val();

  if ( state != '' ) {
    if ( plate != '' ) {
      //if ( subject != '' ) {
        if ( info != '' ) {
          $.ajax({
            type: "POST",
            dataType: "html",
            url: "ajax_add_plate.php",
            //data: "state=" + state + "&plate=" + plate + "&subject=" + subject + "&info=" + info,
            data: "state=" + state + "&plate=" + plate + "&info=" + info,
            success: function(msg) {
              if ( msg == 0 ) {
                alert('Some error occuer. Please try again.');
              } else {
                alert('Plate succesfully published.');

                close_popup();

                window.location = window.location;
              }
            }
          });
        } else {
          alert('Please add info');
        }
      //} else {
        //alert('Please add subject');
      //}
    } else {
      alert('Please add plate');
    }
  } else {
    alert('Please add state!');
  }
}

function check_state() {
  if ( $('#enter_state').val() == 'Enter state..' ) {
    $('#enter_state').val('');
    $('#enter_state').css('color', 'black');
  }
}

function check_plate() {
  if ( $('#enter_plate').val() == 'License plate number...' ) {
    $('#enter_plate').val('');
    $('#enter_plate').css('color', 'black');
  }
}

function submit_search() {
  if ( $('#enter_state').val() != 'Enter state..' || $('#enter_plate').val() != 'License plate number...' ) {
    var allow = false;
    for ( var i = 0; i < other_states.length; i++ ) {
      if ( other_states[i] == $('#enter_state').val() ) {
        allow = true;
        break;
      }
    }

    if ( allow == false ) {
      alert('The state is not correct. Please check your spelling');
    } else {
      window.location = SITE_URL + 'index.php?state=' + $('#enter_state').val() + '&plate=' + $('#enter_plate').val();
    }
  }
}

function upload_file() {
  $('#sent').html('&nbsp;&nbsp;loading...');

  $.ajaxFileUpload (
    {
      url: 'ajax_upload_img.php',
      secureuri: false,
      fileElementId: 'fileToUpload',
      dataType: 'json',
      success: function (data, status) {
        /*
        if(typeof(data.error) != 'undefined') {
          if(data.error != '') {
            alert(data.error);
          }else {
            alert(data.msg);
          }
        }
        */
        $('#fileToUpload').attr('disabled', 'true');

        $('#sent').html('&nbsp;&nbsp;uploaded!');
      },
      error: function (data, status, e) {
        alert(e);
      }
    }
  );

  return false;
}

function check_no_plate() {
  if ( $('#enter_plate').val() != 'License plate number...' ) {
    var plate = $('#enter_plate').val();

    plate = parseText(plate);

    if ( plate.length > 12 ) {
      plate = plate.substring(0, plate.length - 1);
    }

    $('#enter_plate').val(plate);
  }
}

function check_no_plate2() {
  if ( $('#plate').val() != '' ) {
    var plate = $('#plate').val();

    plate = parseText(plate);

    if ( plate.length > 12 ) {
      plate = plate.substring(0, plate.length - 1);
    }

    $('#plate').val(plate);
  }
}

function parseText(text) {
	var accepted_chars = " */-+.~`!@#$%^&*()_-+=[{]};:'\"'|\\,<.>/?";
	
	for ( var i = 0; i < text.length; i++ ) {
    for ( var j = 0; j < accepted_chars.length; j++ ) {
      text = str_replace(accepted_chars.substring(j, j + 1), '', text);
    }
	}
  
	return text;
}

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace
    //
    // version: 1006.1915
    // discuss at: http://phpjs.org/functions/str_replace    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
     for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}}
    }
    return sa ? s : s[0];
}
