window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,clear,count,debug,dir,dirxml,error,exception,firebug,group,groupCollapsed,groupEnd,info,log,memoryProfile,memoryProfileEnd,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());

Function.prototype.bind = function(context) {
	var fn = this;
	return function() {
		return fn.apply(context, arguments);
	};
};


var ls = ls || {};

/**
* Управление всплывающими сообщениями
*/
ls.msg = (function ($) {
	/**
	* Опции
	*/
	this.options = {
		class_notice: 'n-notice',
		class_error: 'n-error'
	};

	/**
	* Отображение информационного сообщения
	*/
	this.notice = function(title,msg){
		$.notifier.broadcast(title, msg, this.options.class_notice);
	};
	
	/**
	* Отображение сообщения об ошибке 
	*/
	this.error = function(title,msg){
		$.notifier.broadcast(title, msg, this.options.class_error);
	};
	
	return this;
}).call(ls.msg || {},jQuery);


/**
* Доступ к языковым текстовкам (предварительно должны быть прогружены в шаблон)
*/
ls.lang = (function ($) {
	/**
	* Набор текстовок
	*/
	this.msgs = {};

	/**
	* Загрузка текстовок
	*/
	this.load = function(msgs){
		$.extend(true,this.msgs,msgs);
	};
	
	/**
	* Отображение сообщения об ошибке 
	*/
	this.get = function(name,replace){
		if (this.msgs[name]) {
			var value=this.msgs[name];
			if (replace) {
				$.each(replace,function(k,v){
					value=value.replace(new RegExp('%%'+k+'%%','g'),v);
				});
			}
			return value;
		}
		return '';
	};
	
	return this;
}).call(ls.lang || {},jQuery);


/**
* Вспомогательные функции
*/
ls.tools = (function ($) {

	/**
	* Переводит первый символ в верхний регистр
	*/
	this.ucfirst = function(str) {
		var f = str.charAt(0).toUpperCase();
		return f + str.substr(1, str.length-1);
	}
	
	/**
	* Выделяет все chekbox с определенным css классом
	*/
	this.checkAll = function(cssclass, checkbox, invert) {
		$('.'+cssclass).each(function(index, item){
			if (invert) {
				$(item).attr('checked', !$(item).attr("checked"));
			} else {
				$(item).attr('checked', $(checkbox).attr("checked"));
			}
		});
	}

	/**
	* Предпросмотр
	*/
	this.textPreview = function(textId, save, divPreview) {
		var text =(BLOG_USE_TINYMCE) ? tinyMCE.activeEditor.getContent()  : $('#'+textId).val();
		ls.ajax(aRouter['ajax']+'preview/text/', {text: text, save: save}, function(result){
			if (!result) {
				ls.msg.error('Error','Please try again later');
			}
			if (result.bStateError) {
				ls.msg.error('Error','Please try again later');
			} else {
				if (!divPreview) {
					divPreview = 'text_preview';
				}
				if ($('#'+divPreview).length) {
					$('#'+divPreview).html(result.sText);
				}
			}
		});
	}
	
	/**
	* Возвращает выделенный текст на странице
	*/
	this.getSelectedText = function(){
		var text = '';
		if(window.getSelection){
			text = window.getSelection().toString();
		} else if(window.document.selection){
			var sel = window.document.selection.createRange();
			text = sel.text || sel;
			if(text.toString) {
				text = text.toString();
			} else {
				text = '';
			}
		}
		return text;
	}
	
	return this;
}).call(ls.tools || {},jQuery);


/**
* Дополнительные функции
*/
ls = (function ($) {
	
	/**
	* Глобальные опции
	*/
	this.options = this.options || {}
	
	/**
	* Выполнение AJAX запроса, автоматически передает security key
	*/
	this.ajax = function(url,params,callback,more){
		more=more || {};
		params=params || {};
		params.security_ls_key=LIVESTREET_SECURITY_KEY;
		
		$.each(params,function(k,v){
			if (typeof(v) == "boolean") {
				params[k]=v ? 1 : 0;
			}
		})
		
		if (url.indexOf('http://')!=0 && url.indexOf('https://')!=0) {
			url=aRouter['ajax']+url+'/';
		}
		
		return $.ajax({
			type: more.type || "POST",
			url: url,
			data: params,
			dataType: more.dataType || 'json',
			success: callback || function(msg){
				ls.debug("base success: ");
				ls.debug(msg);
			}.bind(this),
			error: more.error || function(msg){
				ls.debug("base error: ");
				ls.debug(msg);
			}.bind(this),
			complete: more.complete || function(msg){
				ls.debug("base complete: ");
				ls.debug(msg);
			}.bind(this)
		});
		
	};
	
	/**
	* Выполнение AJAX отправки формы, включая загрузку файлов
	*/
	this.ajaxSubmit = function(url,form,callback,more) {
		more=more || {};	
		if (typeof(form)=='string') {
			form=$('#'+form);
		}
		if (url.indexOf('http://')!=0 && url.indexOf('https://')!=0) {
			url=aRouter['ajax']+url+'/';
		}
		
		var options={
			type: 'POST',
			url: url,
			dataType: more.dataType || 'json',
			data: { security_ls_key: LIVESTREET_SECURITY_KEY },
			success: callback || function(msg){
				ls.debug("base success: ");
				ls.debug(msg);
			}.bind(this),
			error: more.error || function(x,s,e){
				ls.debug("base error: ");
				ls.debug(x);
			}.bind(this)

		}
		
		form.ajaxSubmit(options);
	}

	/**
	* Загрузка изображения
	*/
	this.ajaxUploadImg = function(form, sToLoad) {
		ls.ajaxSubmit('upload/image/',form,function(data){
			if (data.bStateError) {
				ls.msg.error(data.sMsgTitle,data.sMsg);
			} else {
				$.markItUp({ replaceWith: data.sText} );
				$('#form_upload_img').find('input[type="text"], input[type="file"]').val('');
				$('#form_upload_img').jqmHide();
			}
		});
	}
	
	/**
	* Дебаг сообщений
	*/
	this.debug = function(msg) {
		if (this.options.debug) {
			this.log(msg);
		}
	}

	/**
	* Лог сообщений
	*/
	this.log = function(msg) {
		if (window.console && window.console.log) {
			console.log(msg);
		} else {
			//alert(msg);
		}
	}
		
	return this;
}).call(ls || {},jQuery);

(ls.options || {}).debug=1;




jQuery(document).ready(function($){
	
	$('[placeholder]').focus(function() {
      var input = $(this);
      if (input.val() == input.attr('placeholder')) {
        input.val('');
        input.removeClass('placeholder');
      }
    }).blur(function() {
      var input = $(this);
      if (input.val() == '' || input.val() == input.attr('placeholder')) {
        input.addClass('placeholder');
        input.val(input.attr('placeholder'));
      }
    }).blur().parents('form').submit(function() {
      $(this).find('[placeholder]').each(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
        }
      })
    });

    //Верхнее меню
    $("#menu_top li.drop > *:first-child").append("<span class='icon'></span>");

    $("#menu_top li.drop").hover(function() {
            $(this).addClass("active").children(".submenu").show();

            var parent = $(this).parent();

            parent.hover(function() {
            }, function(){
                parent.find("ul.subnav").hide();
            });
        }, function(){
            $(this).removeClass("active").children(".submenu").hide();
    });

    $("a[href*=jpg],a[href*=png]").prettyPhoto({
           social_tools:'',
           show_title: false,
           slideshow:false,
           deeplinking: false
    });

    $("a.highslide").each(function(index,element) {
        var div = $(element).next('.highslide-maincontent'),
            pos = $(element).offset();
        div.dialog({
            autoOpen: false,
            dialogClass: 'tooltip_dialog',
            title: $(element).text(),
            closeText: 'закрыть'
        });
        $(element).click(function(){
            div.dialog("option",{position: [pos.left,pos.top-$(window).scrollTop()-30]}).dialog("open");
            return false;
        });
    });
});
