﻿/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/02/08
 *
 * @author Blair Mitchelmore
 * @version 1.1.2
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});var krapivnik_js=0
if (document.getElementById) {
    var agent=navigator.userAgent.toLowerCase();
    var name="";
    var c=0;
    if (agent.indexOf("opera")!=-1) {
      if (agent.indexOf("mini")==-1) {
            name="opera";c=9;
      }
    } else if (agent.indexOf("msie")!=-1 && document.all) {
      if (agent.indexOf("mac")==-1 && agent.indexOf("j2me")==-1 && agent.indexOf("windows_ce")==-1) {
            name="msie";c=6;
        }
    } else if (agent.indexOf("firefox")!=-1) {
      name="firefox";c=1;
    } else if (agent.indexOf("granparadiso")!=-1) {
        name="granparadiso";c=1;
    } else if (agent.indexOf("shiretoko")!=-1) {
        name="shiretoko";c=1;
    } else if (agent.indexOf("safari")!=-1) {
        name="safari";c=2;
    }
    var i=agent.indexOf(name);
    if (i!=-1 && c>0) {
        var v=parseFloat(agent.substring(i+name.length+1));
        if (!isNaN(v)) krapivnik_js=(v>=c);
    }
}

function convertEntities(o) {
  var c, v;
  c = function(s) {
    if (/&[^;]+;/.test(s)) {
      var e = document.createElement("div");
      e.innerHTML = s;
      return !e.firstChild ? s : e.firstChild.nodeValue;
    }
    return s;
  }

  if ( typeof o === 'string' ) {
    return c(o);
  } else if ( typeof o === 'object' ) {
    for (v in o) {
      if ( typeof o[v] === 'string' ) {
        o[v] = c(o[v]);
      }
    }
  }
  return o;
}

var krapivaCookies = {
  each : function(o, cb, s) {
    var n, l;

    if (!o)
      return 0;

    s = s || o;

    if (typeof(o.length) != 'undefined') {
      for (n=0, l = o.length; n<l; n++) {
        if (cb.call(s, o[n], n, o) === false)
          return 0;
      }
    } else {
      for (n in o) {
        if (o.hasOwnProperty(n)) {
          if (cb.call(s, o[n], n, o) === false) {
            return 0;
          }
        }
      }
    }
    return 1;
  },

  getHash : function(n) {
    var v = this.get(n), h;

    if (v) {
      this.each(v.split('&'), function(v) {
        v = v.split('=');
        h = h || {};
        h[v[0]] = v[1];
      });
    }
    return h;
  },

  setHash : function(n, v, e, p, d, s) {
    var o = '';

    this.each(v, function(v, k) {
      o += (!o ? '' : '&') + k + '=' + v;
    });

    this.set(n, o, e, p, d, s);
  },

  get : function(n) {
    var c = document.cookie, e, p = n + "=", b;

    if (!c)
      return;

    b = c.indexOf("; " + p);

    if (b == -1) {
      b = c.indexOf(p);

      if (b != 0)
        return null;

    } else {
      b += 2;
    }

    e = c.indexOf(";", b);

    if (e == -1)
      e = c.length;

    return decodeURIComponent(c.substring(b + p.length, e));
  },

  set : function(n, v, e, p, d, s) {
    document.cookie = n + "=" + encodeURIComponent(v) +
      ((e) ? "; expires=" + e.toGMTString() : "") +
      ((p) ? "; path=" + p : "") +
      ((d) ? "; domain=" + d : "") +
      ((s) ? "; secure" : "");
  },

  remove : function(n, p) {
    var d = new Date();

    d.setTime(d.getTime() - 1000);

    this.set(n, '', d, p, d);
  }
};
function getUserSetting( name, def ) {
  var o = getAllUserSettings();

  if ( o.hasOwnProperty(name) )
    return o[name];

  if ( typeof def != 'undefined' )
    return def;

  return '';
}

function setUserSetting( name, value, del ) {
  if ( 'object' !== typeof userSettings )
    return false;

  var c = 'settings-' + userSettings.uid, o = krapivaCookies.getHash(c) || {}, d = new Date(), p,
  n = name.toString().replace(/[^A-Za-z0-9_]/, ''), v = value.toString().replace(/[^A-Za-z0-9_]/, '');

  if ( del ) {
    delete o[n];
  } else {
    o[n] = v;
  }

  d.setTime( d.getTime() + 31536000000 );
  p = userSettings.url;

  krapivaCookies.setHash(c, o, d, p);
  krapivaCookies.set('settings-time-'+userSettings.uid, userSettings.time, d, p);

  return name;
}

function deleteUserSetting( name ) {
  return setUserSetting( name, '', 1 );
}

function getAllUserSettings() {
  if ( 'object' !== typeof userSettings )
    return {};

  return krapivaCookies.getHash('settings-' + userSettings.uid) || {};
}
function textCounter( field, countfield, maxlimit ) {  
  if ( field.value.length > maxlimit )
  {
    field.value = field.value.substring( 0, maxlimit );    
    return false;
  }
  else
  {
    
    $(countfield).html(maxlimit - field.value.length);
  }
}

function captcha_refresh(elem,url){
    
    var div         = $(elem).parents("div[id^='captcha_']");
    var refresh_url = '';
    if(!url){
       refresh_url = $(elem).parents('form').attr('action');
       refresh_url = refresh_url.replace(dir_base,'');
       refresh_url = dir_base + refresh_url.replace('\/add','')+'/captcha_refresh';
    }else{
        refresh_url = url;
    }
    div.ajax_throbber();
    $.post( refresh_url,
        function( data ) {            
            div.html(data);            
        }
    );/**/
    return false;
}
  function switch_throbber(element,url) {
    var old_value   = $(element).html();
    if ( url.lengh == 0 ) {
      return true;
    } else {
        $( element ).ajax_throbber();

      $.post( url, {},function( data ) {
        var content = ''; 
        if(data.length < 1 || (data !='true' && data!='false')){
          content = old_value;
        }else if(data == 'true'){
          content = 'ДА';
        }else if(data == 'false'){
          content = 'НЕТ';
        }
        $(element).html( content );
      });
    }
  }


RegExp.escape = function( text ) {
            if (!arguments.callee.sRE) {
              var specials = [
                  '/', '.', '*', '+', '?', '|', '^', '$',
                  '(', ')', '[', ']', '{', '}', '\\'
              ];
              arguments.callee.sRE = new RegExp( '(\\' + specials.join('|\\') + ')', 'g' );
              }
              return text.replace(arguments.callee.sRE, '\\$1');
          }

jQuery.fn.ajax_throbber = function() {
              this.html( '<span class="ajax_throbber"><img src="'+dir_icon+'/misc/throbber.gif"></span>' );
              //alert(dir_icon+"/misc/throbber.gif")
              };

function include(script_filename) {
  document.write('<' + 'script');
  document.write(' language="javascript"');
  document.write(' type="text/javascript"');
  document.write(' src="' + script_filename + '">');
  document.write('</' + 'script' + '>');
}

function acl_toggle( name ) {
  var check_boxes = $( "."+name+":checkbox" );
  if ( check_boxes.size() != check_boxes.filter( ":checked" ).size() ) {
    $( "."+name+":checkbox" ).each(
                    function() { $(this).attr( "checked", "checked" ); }
                    );
  } else {
    $( "."+name+":checkbox" ).each(
                    function() { $(this).removeAttr( "checked" ); }
                    );
  }
}

function confirm_delete() {
  $( ".confirm_del" ).click(
              function() {
                var answer = confirm( "Вы уверены в том что хотите продолжить?" );
                return answer;
              }
            );
}
function check_delete() {
  $( ".check_delete" ).click(
              function() {
                var answer = confirm( "Вы уверены в том что хотите продолжить?" );
                return answer;
              }
            );
}

function events(){
        $('#events').each(function(){
           var block = $(this);
           if(block.length>0){
               block.oneTime('15s',function(){
                    $(this).fadeOut(5000);
               });
           }
        });
    return false;
  };

$( document ).ready( confirm_delete );
$( document ).ready( events );
$( document ).ready( check_delete );
$( document ).ready(function(){
    var elem = $('#search');
        var stext = elem.val();

        $('#ajax_throbber').hide();
        $('#busy_layer').hide();
        
        elem.focus(function(){
            if (elem.val()==stext) {
                elem.val('');                
            }
        });

        elem.blur( function(){
            if (elem.val()=='') {
                elem.val(stext);
            }
        });
});