/*  String handlers  */
jQuery.extend(String.prototype, {

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : String(this);
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = new Element('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return { };

    return match[1].split(separator || '&').inject({ }, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  times: function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },
  /*
  isJSON: function() {
    var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },
  */
  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return /^\s*$/.test(this);
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  }
});

function isEmpty(input_id, setFocus){
	setFocus = typeof(setFocus) == 'undefined' ? false : true;

	if ($('#'+input_id).val().blank()){
		if (setFocus){
			$('#'+input_id).focus();
		}
		return true;
	}
	return false;
}

function isEmail(el_id) {
	var email = $('#'+el_id);
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{1,4})+$/;
	if (!filter.test(email.val())) {
		email.focus();
		return false;
	}

	return true;
}

function formToJSON(form_id){
	var obj = new Object();
	var formData = $('#'+form_id).serializeArray();

	try{
		for(var i in formData){
			obj[formData[i].name] = formData[i].value;
		}
	}
	catch(e){}

	return obj;
}

function onlyDigits(evt){
	var charCode = (evt.which) ? evt.which : evt.keyCode
     if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

     return true;
}

function showCalendar(id, defaultDate){
	var date = null;
	if (typeof defaultDate != 'undefined' || !defaultDate.blank()){
		date = $.datepicker.parseDate('yy-mm-dd', defaultDate);
	}

	$('#'+id).datepicker({
		showOn: 'button',
		buttonImage: '../images/calendar.gif',
		buttonImageOnly: true,
		dateFormat : 'yy-mm-dd',
		defaultDate : date

	});
}

/**
 * Clear form elements' values
 * @param formId
 * @return void(0)
 */
function clearForm(formId){
    $(':input','#' + formId + '')
    .not(':button, :submit, :reset, :hidden')
    .val('')
    .removeAttr('checked')
    .removeAttr('selected');
}

/**
 * Clear form elements' values
 * @param formId
 * @return void(0)
 */
function selectAllCheckbox(formId, property){
    if(property == true){
  //    $(":input:checkbox:enabled").attr('checked', true);
        $(':input','#' + formId+ '').attr('checked', true);
        $('#delete_selected').attr('disabled', false);
    } else {
//      $(":input:checkbox:enabled").attr('checked', false);
        $(':input','#' + formId+ '').attr('checked', false);
        $('#delete_selected').attr('disabled', true);
    }
}

function setButtonDisplay(formId){
    if($("input:checked").length >=1){
        $('#delete_selected').attr('disabled', false);
    } else {
            $('#delete_selected').attr('disabled', true);
    }
}

jQuery.extend({
	 serialize: function ( mixed_value ) {
	 // Returns a string representation of variable (which can later be unserialized)
	 //
	 // version: 906.1807
	 // discuss at: http://phpjs.org/functions/serialize
	 // +   original by: Arpad Ray (mailto:arpad@php.net)
	 // +   improved by: Dino
	 // +   bugfixed by: Andrej Pavlovic
	 // +   bugfixed by: Garagoth
	 // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
	 // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
	 // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
	 // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
	 // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
	 // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
	 // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
	 // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
	var _getType=function(inp){var type=typeof inp,match;var key;if(type=='object'&&!inp){return'null'}if(type=="object"){if(!inp.constructor){return'object'}var cons=inp.constructor.toString();match=cons.match(/(\w+)\(/);if(match){cons=match[1].toLowerCase()}var types=["boolean","number","string","array"];for(key in types){if(cons==types[key]){type=types[key];break}}}return type};var type=_getType(mixed_value);var val,ktype='';switch(type){case"function":val="";break;case"boolean":val="b:"+(mixed_value?"1":"0");break;case"number":val=(Math.round(mixed_value)==mixed_value?"i":"d")+":"+mixed_value;break;case"string":val="s:"+encodeURIComponent(mixed_value).replace(/%../g,'x').length+":\""+mixed_value+"\"";break;case"array":case"object":val="a";var count=0;var vals="";var okey;var key;for(key in mixed_value){ktype=_getType(mixed_value[key]);if(ktype=="function"){continue}okey=(key.match(/^[0-9]+$/)?parseInt(key,10):key);vals+=$.serialize(okey)+$.serialize(mixed_value[key]);count++}val+=":"+count+":{"+vals+"}";break;case"undefined":default:val="N";break}if(type!="object"&&type!="array"){val+=";"}return val}
});

//------------MOSKOW--------------//

function photos(id, type){
  var url = "/photos/"+type+"/"+id+"/";
  var prop = "height=600,width=750,location=none," + "scrollbars=no,menubars=no,toolbars=no,resizable=no,fullscreen=no";
  window.open(url, 'Фото', prop);
}

function map(id, type){
  var url = "/map/"+type+"/"+id+"/";
  var prop = "height=300,width=500,location=none," + "scrollbars=no,menubars=no,toolbars=no,resizable=no,fullscreen=no";
  window.open(url, 'Карта', prop);
}

function selectel(id)
{
	document.getElementById('i'+id).checked = !document.getElementById('i'+id).checked;
	document.getElementById('all').checked = false;
}

function dlot(type, id)
{
	var url = "delete.php?type="+type+"&id="+id;
	var prop = "height=1,width=1,location=none," + "scrollbars=no,menubars=no,toolbars=no,resizable=no,fullscreen=no";
	window.open(url, 'Delete', prop);
}

function dfromslider(id, type)
{
	var url = "slider.php?type="+type+"&id="+id;
	var prop = "height=1,width=1,location=none," + "scrollbars=no,menubars=no,toolbars=no,resizable=no,fullscreen=no";
	window.open(url, 'Delete', prop);
}

function photod(type, id) {
	var url = "photod.php?type="+type+"&id="+id;
	var prop = "height=1,width=1,location=none," + "scrollbars=no,menubars=no,toolbars=no,resizable=no,fullscreen=no";
	window.open(url, 'Delete', prop);
}


