
function load_url(url){
    if (url) document.location.href = url;
}

/*bookmarks this page*/
function addbookmark() {
    var tytul = document.title;
    var adres = document.location;

    //FireFox
    if (window.sidebar) { 
        window.sidebar.addPanel(tytul, adres, ""); 
    //IE
    } else if (window.external) {
        window.external.AddFavorite(adres, tytul); 
    //Opera
    } else if (window.opera && window.print) {
        var a = document.createElement('a');
        a.setAttribute('href', adres);
        a.setAttribute('title', tytul);
        a.setAttribute('rel','sidebar');
        a.click();
    }
}

/*for include js file*/
function include(script_filename) {
    document.write('<' + 'script');
    document.write(' language="javascript"');
    document.write(' type="text/javascript"');
    document.write(' src="' + script_filename + '">');
    document.write('</' + 'script' + '>');
}
/*include js file after page load*/
function include_dom(script_filename) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var js = document.createElement('script');
    js.setAttribute('language', 'javascript');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', script_filename);
    html_doc.appendChild(js);
    return false;
}

function slideSwitch(id) {
    var $active = $('#slideshow'+id+' li.active');
    if ( $active.length == 0 ) $active = $('#slideshow'+id+' li:last');
    var $next =  $active.next().length ? $active.next()
        : $('#slideshow'+id+' li:first');
    $active.addClass('last-active');
    $active.animate({opacity: 0.0}, 1000, function() {
    	$active.css('display','none');
    	$next.css({opacity: 0.0,display: 'block'})
       		.addClass('active')
        	.animate({opacity: 1.0}, 1000, function() {
     	       	$active.removeClass('active last-active');
    	});
    });
}

/*check if it Json*/
function IsJsonString(str){
    try{
        JSON.parse(str);
    }catch (e){
        return false;
    }
    return true;
}


var PHP = {
	dirname: function(path){
		return path.replace(/\\/g,'/').replace(/\/[^\/]*\/?$/, '');
	},
	basename: function(path, suffix) {
    	var b = path.replace(/^.*[\/\\]/g, '');
        if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        	b = b.substr(0, b.length-suffix.length);
    	}	
    	return b;
    },
    addslashes: function(str){
		str=str.replace(/\\/g,'\\\\');
		str=str.replace(/\'/g,'\\\'');
		str=str.replace(/\"/g,'\\"');
		str=str.replace(/\0/g,'\\0');
		return str;
	},
	stripslashes: function(str){
		str=str.replace(/\\'/g,'\'');
		str=str.replace(/\\"/g,'"');
		str=str.replace(/\\0/g,'\0');
		str=str.replace(/\\\\/g,'\\');
		return str;
	},
	in_array: function(what, where){
    	var a=false;
    	for(var i=0;i<where.length;i++){
    		if(what == where[i]){
    			a=true;
    			break;
    		}
    	}
    	return a;
    }
};

function Load(){
	this.tinymce = function(){
		include(GLOBAL__PATH_JAVASCRIPT+"tiny_mce/plugins/tinybrowser/tb_tinymce.js.php");
		include(GLOBAL__PATH_JAVASCRIPT+"tiny_mce/jquery.tinymce.js");
		$(document).ready(function() {
			$('textarea.tinymce').tinymce({
				file_browser_callback : "tinyBrowser",
				script_url : GLOBAL__PATH_JAVASCRIPT+'tiny_mce/tiny_mce.js',
				init_instance_callback: function(inst){
					Lang.SetLangContent();
					Page.SetMyTooltip();
					Notification.setTinyError($(this).attr('id'));
				},
				// General options
				theme : "advanced",language : "en",mode : "exact",
				skin : "o2k7",skin_variant : "silver",
				//cleanup : false, //important for templates
				force_p_newlines : false,
				force_br_newlines : true,
				forced_root_block : '',
				plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				
				theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
				theme_advanced_buttons2 : "template,|,pastetext,pasteword,|,search,replace,|,outdent,indent,|,bullist,numlist,|,forecolor,backcolor,|,link,unlink,anchor,image,|,sub,sup,charmap,hr,|,code,preview,fullscreen",
				theme_advanced_buttons3 : "tablecontrols,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,attribs,|,ltr,rtl,|,undo,redo,|,removeformat,visualaid",
				
				theme_advanced_toolbar_location : "top",theme_advanced_toolbar_align : "left",theme_advanced_statusbar_location : "bottom",
				theme_advanced_resizing : true,			

				content_css : GLOBAL__PATH_CSS+"style.articles.css",
				template_external_list_url : TINY_MCE_TEMPLATE_FILE,
				external_link_list_url : TINY_MCE_LINK_FILE,
				external_image_list_url : "lists/image_list.js",
				media_external_list_url : "lists/media_list.js",
				font_size_style_values : "8px,11px,12px,13px,14px,16px,18px",
				template_replace_values : {
					username : "Some User",
					staffid : "991234"
				}
			});
		});
	};
	
	this.datepicker = function(el,format){
   		include("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js");
		$(document).ready(function(){
			$(el).datepicker({ dateFormat: format});
		});
	};
}


var GMaps = {
	SelectIcon: function(id_point){
		var params = $('#point_icon_'+id_point).val();
		$.floatbox({
       		 ajax: {
            	url: URL_MAP_ADD_ICON+'&id_point='+id_point+((params)?'&params='+params:''),
           		before: "<p>"+LangJs['_LOADING']+"</p>"
       	 	},
        	fade: true,
       		bgConfig : {opacity: "0.2"}
    	});	
    },
    ResponseSelectIcon: function(id_point,Response){
    	$('#point_icon_'+id_point).val(Response);
    	R = JSON.parse(Response);
    	if(R.icon_image){
    		$('#icon_info_'+id_point+' span').html('(<a href="javascript:GMaps.SelectIcon(\''+id_point+'\');void(null);" >'+R.icon_image+'</a>)');
    	}
    	$.floatbox({destroy: true});
    },
    ChooseImage: function(el,path){
    	$('.icon_maps_list a').removeClass('selected');
    	$(el).addClass('selected');
    	$('#icon_image').val(path);
    },
    AddNext: function(){
    	var last_id = $('.point:last').attr('id').replace('point_','');
    	var id = parseInt(last_id)+1;
    	$('<ul id="point_'+id+'" class="form_list point">'+	
    			'<li class="head head-slim"><label for="point_center_'+id+'">'+LangJs['_MAP_CENTER']+':</label></li>'+
		  		'<li class="data data-slim"><input type="checkbox" onclick="GMaps.SetCenter($(this));" class="checkbox point-center" value="1" id="point_center_'+id+'" name="point['+id+'][center]" clas="point-center" ></li><li class="clear">&nbsp;</li>'+
				'<li class="head head-slim"><label for="point_address_'+id+'">'+LangJs['_MAP_ADDRESS']+':</label></li>'+
		  		'<li class="data data-slim"><input type="text" class="text" value="" id="point_address_'+id+'" name="point['+id+'][address]"></li><li class="clear">&nbsp;</li>'+
				'<li class="head head-slim"><label for="point_lat_'+id+'">'+LangJs['_MAP_COORDINATES']+':</label></li>'+
				'<li class="data data-slim">'+
					'<input type="text" value="" style="width: 200px;" name="point['+id+'][lat]" id="point_lat_'+id+'" class="text">&nbsp;'+
					'<input type="text" value="" style="width: 200px;" name="point['+id+'][lng]" id="point_lng_'+id+'" class="text">'+
				'</li><li class="clear">&nbsp;</li>'+
				'<li class="head head-slim"><label for="point_html_'+id+'">'+LangJs['_MAP_HTML']+':</label></li>'+
		  		'<li class="data data-slim"><textarea id="point_html_'+id+'" name="point['+id+'][html]"></textarea></li><li class="clear">&nbsp;</li>'+
				'<li class="head head-slim">&nbsp;</li>'+
				'<li class="data data-slim">'+
				'	<input type="button" value="'+LangJs['_MAP_SELECT_ICON_IMAGE']+'" class="button-white" onclick="GMaps.SelectIcon(\''+id+'\');">'+
				'	<span id="icon_info_'+id+'">'+
				'		<input type="hidden" value="" id="point_icon_'+id+'" name="point['+id+'][icon]">'+
				'		<span class="info"></span>'+
				'	</span>'+
				'</li><li class="clear">&nbsp;</li>'+
				'<li class="hr">&nbsp;</li>'+
		'</ul>').insertAfter('ul.point:last');
    	Page.SetBorderForInput();
    },
    SetCenter: function(el){
    	$('.point-center').attr('checked',false);
    	$(el).attr('checked', true);
    },
    RemoveLast: function(){
    	if($('ul.point').length > 1){
    		$('ul.point:last').remove();
    	}
    },
    ChangeStatus: function(id,value){
		if(id){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$.post(URL_MAP_CHANGE_STATUS, "id="+id+"&value="+value, function(theResponse){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success == true){
					$('.status-'+id).val(value);
					if(value != 1){$('.tr_'+id).addClass('tr_red');
					}else{$('.tr_'+id).removeClass('tr_red');}
				}else if(theResponse.error){Notification.error(theResponse.error);}
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}); 		
		}
	}
};

var Translator = {
	Show: function(lang,duration){
		if(!duration) duration = "fast";
		if(lang){
			Notification.loader('div#topmenu .top','small');
			if($('#translator-'+lang).css('display') == 'none'){
				if(Translator.CloseAll()){
					$('#item-'+lang+' .close').attr('class','open');
					$('#translator-'+lang).slideDown(duration,function(){Notification.removeLoader('div#topmenu .top','small');});
					return true;
				}
			}else{
				if($('#translator-'+lang+' #hidden-box-'+lang+'-2 .change').size()){
					if(!confirm(LangJs['_ARE_YOU_SURE_YOU_WANT_TO_CLOSE_OPEN_CARD'])) return false;
				}
				$('#item-'+lang+' .open').attr('class','close');
				$('#translator-'+lang).slideUp(duration,function(){
					$.cookie('tolang',false);
					Notification.removeLoader('div#topmenu .top','small');
				});
				$('#translator-'+lang+' .hidden-box').html('');
				return false;
			}
		}
	},
	CloseAll: function(){
		var changes = 0;
		$('.translator').each(function(){
			var id = $(this).attr('id');
			if($(this).css('display') == 'block' && $('#'+id+' .change').size()){
				changes++;
			}
		});
		if(changes){
			if(confirm(LangJs['_ARE_YOU_SURE_YOU_WANT_TO_CLOSE_OPEN_CARD'])){
				$('.translator .hidden-box').html('');
				$('.translator').css('display','none');
				$('.item .open').attr('class','close');
			}else{return false;}
		}else{
			$('.translator .hidden-box').html('');
			$('.translator').css('display','none');
			$('.item .open').attr('class','close');
		}
		return true;
	},
	SetAutoScroll: function(lang){
		if(lang){
			$('#hidden-box-'+lang).scroll(function(){
    			$('#hidden-box-'+lang+'-2').scrollTop($(this).scrollTop());
			});
			$('#hidden-box-'+lang+'-2').scroll(function(){
    			$('#hidden-box-'+lang).scrollTop($(this).scrollTop());
			});
		}
	},
	LoadLang: function(fromLang,toLang,type,readonly){
		Notification.loader('div#topmenu .top','small');
		if(fromLang){$('#translator-'+toLang+' .from').val(fromLang);}
		if(type){$('#translator-'+toLang+' .type').val(type);}
		$.post(URL_LOAD_LANG,'lang='+((readonly)?fromLang:toLang)+'&type='+type+'&readonly='+readonly, function(theResponse){
			if(readonly){
				$('#hidden-box-'+toLang).html(theResponse);
				Translator.SetEventFrom(toLang);
			}else{
				$('#hidden-box-'+toLang+'-2').html(theResponse);
				Translator.SetEventTo(toLang);
			}
			$.cookie('tolang',toLang);
			var arrLang = ($.cookie('langs'))?JSON.parse($.cookie('langs')):{};
			if(!arrLang[toLang]) arrLang[toLang] = {};
			arrLang[toLang]['to'] 	= toLang;
			arrLang[toLang]['from'] = fromLang;
			arrLang[toLang]['type'] = type;
			$.cookie('langs',JSON.stringify(arrLang));
			Notification.removeLoader('div#topmenu .top','small');
		});
	},
	/*function return array with langs params*/
	GetArrayLang: function(lang){
		var arrLang = ($.cookie('langs'))?JSON.parse($.cookie('langs')):"";
		return (arrLang[lang])?arrLang[lang]:"";
	},
	/*set event for inputs in translator box from*/
	SetEventFrom: function(toLang){
		$('#hidden-box-'+toLang+' .it').click(function(){
			if(!$(this).hasClass('active'))$(this).addClass('active');
			else $(this).removeClass('active');
		});
		$('#hidden-box-'+toLang+' .it').mouseover(function(){
			if(!$(this).hasClass('hover'))$(this).addClass('hover');
		});
		$('#hidden-box-'+toLang+' .it').mouseout(function(){
			$(this).removeClass('hover');
		});
		//TODO: make select all(not ctrl_a)
		/*ctrl+a listener*/
		/*$(document).keydown(function(e){
			if(e.keyCode == 65 && e.ctrlKey){
				$('#hidden-box-'+toLang+' .it').addClass('active');
			}
		});*/
	},
	SetEventTo: function(toLang){
		$('#hidden-box-'+toLang+'-2 .it input').focus(function(){
			if(!$(this).parent().hasClass('active'))$(this).parent().addClass('active');
		});
		$('#hidden-box-'+toLang+'-2 .it input').blur(function(){
			$(this).parent().removeClass('active');
		});
		$('#hidden-box-'+toLang+'-2 .it input').change(function(){
			if(!$(this).parent().hasClass('change'))$(this).parent().addClass('change');
		});
		$('#translator-'+toLang+' #auto-translate').click(function(){
			Translator.Translate(toLang);
		});
	},
	/*auto translate with google translator*/
	Translate: function(toLang){
		Notification.loader('div#topmenu .top','small');
		Translator.Fade('out',toLang);
		var arrLang = Translator.GetArrayLang(toLang);
		var selected = $('#hidden-box-'+toLang+' .active').size();
		var completed = 0;
		$('#hidden-box-'+toLang+' .active').each(function(){
			var self = this;
			$.post(URL_TRANSLATE,{ "from": ((arrLang['from'])?arrLang['from']:""), "to": toLang, "text": $(self).children('input').val()}, function(theResponse){
				if(theResponse){
					var id = $(self).attr('id').substr(1).replace(":","\\:");
					$('#'+id).val(theResponse);
					$(self).removeClass('active');
					if(!$('#'+id).parent().hasClass('change'))$('#'+id).parent().addClass('change');
				}
				completed++;
				if(completed == selected){
					Notification.removeLoader('div#topmenu .top','small');
					Translator.Fade('in',toLang);
				}
			});
		});
		if(!selected){
			Notification.error(LangJs['_TEXT_NOT_SELECTED']);
			Notification.removeLoader('div#topmenu .top','small');
			Translator.Fade('in',toLang);
		};
	},
	Load: function(toLang){
		if(toLang){
			var arrLang = Translator.GetArrayLang(toLang);
			if(Translator.Show(toLang,"fast")){
				Translator.LoadLang((arrLang['from'])?arrLang['from']:'',toLang,(arrLang['type'])?arrLang['type']:'',1);
				Translator.LoadLang((arrLang['from'])?arrLang['from']:'',toLang,(arrLang['type'])?arrLang['type']:'',0);
				Translator.SetAutoScroll(toLang);
			}
		}
	},
	Change: function(toLang){
		if(toLang){
			var arrLang = Translator.GetArrayLang(toLang);
			var from = $('#translator-'+toLang+' select.from').val();
			var type = $('#translator-'+toLang+' select.type').val();
			Translator.LoadLang(from,toLang,type,1);
			Translator.LoadLang(from,toLang,type,0);
			Translator.SetAutoScroll(toLang);
		}
	},
	Save: function(toLang){
			Notification.loader('div#topmenu .top','small');
			Translator.Fade('out',toLang);
		$('#form-'+toLang).ajaxSubmit(function(jsonResponse){
			jsonResponse = JSON.parse(jsonResponse);
			if(jsonResponse.success){
				Notification.success(jsonResponse.message);
				$('#translator-'+toLang+' #hidden-box-'+toLang+'-2 .it').removeClass('change');
			}
			if(jsonResponse.error)Notification.error(jsonResponse.error);
			Notification.removeLoader('div#topmenu .top','small');
			Translator.Fade('in',toLang);
		});
	},
	Fade: function(type,toLang){
		if(type == 'out'){$('#translator-'+toLang).fadeTo('fast',0.5);}
		if(type == 'in'){$('#translator-'+toLang).fadeTo('fast',1);}
	}
};

var Uploader = {
	Ins: Array(),
	Init: function(sid,type,count,sizeLimit,exist){
		Uploader.Ins[sid] = new qq.FileUploader({
                element: document.getElementById('qq'+sid),
               	allowedExtensions:(type == 'graphics')?['jpg','jpeg','png','gif']:[],
                action: URL_UPLOADER,
                debug: false,
                sizeLimit: sizeLimit,
                existingFiles: exist,
                onSubmit: function(){
                	Notification.removeAllSlow();
                },
                onComplete: function(id, fileName, responseJSON){
                	if(responseJSON.success != true){
                		$('#qq'+sid+' .qq-upload-list').children(':eq('+(id)+')').hide();
                	}else{
                		Page.SetMyTooltip();
                		Uploader.SetParameters(id,fileName,responseJSON,sid,type);
                		Page.SetLightbox('fast');
                		Uploader.Move(sid,type);
                	}
                },
                params: {
                	sid: sid,
                	count: (count)?count:null,
                	type: (type)?type:null
                },
                messages: {
            		typeError: LangJs['_UPLOADER_TYPE_ERROR'],
            		sizeError: LangJs['_UPLOADER_SIZE_ERROR'],
            		minSizeError: LangJs['_UPLOADER_MIN_SIZE_ERROR'],
            		emptyError: LangJs['_UPLOADER_EMPTY_ERROR'],
            		onLeave: LangJs['UPLOADER_ON_LEAVE']            
        		},
                showMessage: function(message){Notification.error(message,'#qq'+sid);}  
		});
	},
	Move: function(sid,type){
		$("#qq"+sid+" .qq-upload-list").sortable({ opacity: 0.6, cursor: 'move',handle: '',  update: function(){
			var data = $(this).sortable("serialize"); 
			Uploader.FadeOut(sid);
			$.post(URL_UPLOADER_MOVE, data+'&sid='+sid, function(theResponse){
				Uploader.SetAllParams(sid,type);
				Uploader.FadeIn(sid);
			});
		}});
	},
	SetAllParams: function(sid,type){
		$("#qq"+sid+" .qq-upload-list li").each(function(index){
			$(this).attr('id','recordsArray_'+index);
			$("#qq"+sid+" #recordsArray_"+index+" .edit").unbind('click');
			$("#qq"+sid+" #recordsArray_"+index+" .delete").unbind('click');
			$("#qq"+sid+" #recordsArray_"+index+" .edit").click(function(){Uploader.EditTitle(index,sid,type);});
			$("#qq"+sid+" #recordsArray_"+index+" .delete").click(function(){Uploader.Delete(index,sid);});
		});
	},
	SetParameters: function(id,fileName,responseJSON,sid,type){
		$("#qq"+sid+" .qq-upload-list").children(':eq('+id+')').attr('id','recordsArray_'+id);
		$("#qq"+sid+" #recordsArray_"+id+" .edit").click(function(){Uploader.EditTitle(id,sid,type);});
		$("#qq"+sid+" #recordsArray_"+id+" .delete").click(function(){Uploader.Delete(id,sid);});
		
		if(responseJSON.url && type == 'graphics') $("#recordsArray_"+id).css('background','url(\''+responseJSON.url+'\') no-repeat 0 0');
		if(type == 'graphics'){
			$("#qq"+sid+" #recordsArray_"+id+" .show").attr({'href':responseJSON.url_big, 'rel':'lightbox'});
		}else{
			$("#qq"+sid+" #recordsArray_"+id+" .show").attr({'href':responseJSON.url, 'target':'_blank'});
           	$('#qq'+sid+' #recordsArray_'+id+' .qq-upload-file').html(fileName);
		}
		
	},
	Delete: function(id,sid){
		$('#qq'+sid+' #recordsArray_'+id).css('background','#f3f3f3');
		if(!$('#qq'+sid+' #recordsArray_'+id+' .qq-upload-spinner').length)$('#qq'+sid+' #recordsArray_'+id).prepend('<div class="qq-upload-spinner"></div>');
		$('#qq'+sid+' #recordsArray_'+id).fadeTo('slow',0.4);
		$.post(URL_UPLOADER_DELETE, 'id='+id+'&sid='+sid, function(theResponse){
			$('#qq'+sid+' #recordsArray_'+id+' .qq-upload-spinner').remove();
			$('#qq'+sid+' #recordsArray_'+id+' a.show').removeAttr('rel');
			$('#qq'+sid+' #recordsArray_'+id).hide();
			Page.SetLightbox('fast');
		}); 	
	},
	EditTitle: function(id,sid,type){
		$.floatbox({
       		 ajax: {
            	url: URL_UPLOADER_EDIT+'&id='+id+'&sid='+sid+'&type='+type,
           		before: "<p>"+LangJs['_LOADING']+"</p>" //loading message while the request is being processed
       	 	},
        	fade: true,
       		bgConfig : {opacity: "0.2"}
    	});	
	},
	ResponseEditTitle: function(Response){
		Response = JSON.parse(Response);
		if(Response.success == 'true'){
           if(Response.type != 'graphics' && Response.id && Response.title){
           		var el = $('#qq'+Response.sid+' #recordsArray_'+Response.id+' .qq-upload-file');
           		var url =  ($(el).children('span').html())?$(el).children('span').html():$(el).html();
           		$('#qq'+Response.sid+' #recordsArray_'+Response.id+' .qq-upload-file').html('<b>'+Response.title+'</b> [<span>'+url+'</span>]');
           	}else if(Response.type == 'graphics' && Response.id){
           		if(Response.url)$("#qq"+Response.sid+" #recordsArray_"+Response.id).css('background','url("'+Response.url+'") no-repeat 0 0');
           		if(Response.url_big)$("#qq"+Response.sid+" #recordsArray_"+Response.id+" a.show").attr('href',Response.url_big);
           	}
		}else if(Response.error){
			Notification.error(Response.error);
		}
		$.floatbox({destroy: true});
	},
	FadeOut: function(sid,value){
		if(!value) value = 0.4;
		$('#qq'+sid+' .qq-upload-list').fadeTo('fast',value);
	},
	FadeIn: function(sid,value){
		if(!value) value = 1;
		$('#qq'+sid+' .qq-upload-list').fadeTo('fast',value);
	},
	
	/*crop function*/
	Jcrop: null,
	SetCrop: function(){
		if(this.Jcrop == null){
			this.Jcrop = $.Jcrop('.cropbox img',{
				onChange: Uploader.UpdateCropCoords
			});
		}
	},
	DestroyCrop: function(){
		if(this.Jcrop != null){
			this.Jcrop.destroy();
			this.Jcrop = null;
			$('#x,#y,#w,#h').val('');
		}
	},
	UpdateCropCoords: function(c){
		$('#x').val(c.x);
		$('#y').val(c.y);
		$('#w').val(c.w);
		$('#h').val(c.h);
	},
	SetResizer: function(imgId){
		$('.resizer #height').keyup(function(ev){integer(this);(isInteger($(this).val()))?Uploader.Resize(imgId, 'h'):'';});
		$('.resizer #width').keyup(function(ev){integer(this);(isInteger($(this).val()))?Uploader.Resize(imgId, 'w'):'';});
		
		$('.resizer #height').val($(imgId).height());
		$('.resizer #width').val($(imgId).width());
	},
	DestroyResizer: function(imgId){
		if(this.ResizeHeight && this.ResizeWidth){
			$(imgId).css({'height':this.ResizeHeight+'px','width':this.ResizeWidth+'px'});
			this.ResizeHeight = this.ResizeWidth = null;
			$('.resizer #height').val('');
			$('.resizer #width').val('');
		}
	},
	ResizeHeight: null,
	ResizeWidth: null,
	Resize: function(imgId, flag){
		var height = (!this.ResizeHeight)?$(imgId).height():this.ResizeHeight;
		var width = (!this.ResizeWidth)?$(imgId).width():this.ResizeWidth;
		if(flag == 'h'){
			var heightN = $('.resizer #height').val();
			var widthN = width*(heightN/height); 
		}else{
			var widthN = $('.resizer #width').val();
			var heightN = height*(widthN/width);
		}
		if(!heightN)heightN = 0;
		if(!widthN)widthN = 0;
		if(heightN <= height && widthN<= width){
			$('.resizer #height').val(parseInt(heightN));
			$('.resizer #width').val(parseInt(widthN));
			$(imgId).css({'height':heightN+'px','width':widthN+'px'});
		}else{
			$(imgId).css({'height':height+'px','width':width+'px'});
			Notification.alert(LangJs['_UPLOADER_RESIZER_ERROR_TO_BIG_SIZE']);
		}
		this.ResizeHeight = height;
		this.ResizeWidth = width;
	}
};

var Menu = {
	Position: function(){
		$("div.sortable").sortable({ opacity: 0.6, cursor: 'move',handle: 'span.position',  update: function() {
			var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_POSITION, data, function(theResponse){
					Lang.FadeIn();
					$('.m').html(theResponse);
					Page.SetMyTooltip();
					Notification.removeLoader('div#topmenu .top','small');}); 															 
			}								  
		});
	},
	Move: function(){
	$('div.parent,div.child').droppable(
			{
				accept			: 'div.cat_2,div.cat',
				hoverClass		: 'dropOver',
				activeClass		: 'fakeClass',
				tolerance		: 'pointer',
				drop			: function(event, ui)
				{
					var parDepth = $(this).parents('.cat_2,.cat').length;
					if(MENU_MAX_DEPTH > parDepth){
						var parent = $(this).attr('id').substr(4);
						var child =  ui.draggable.attr('id').substr(13).split(':');
						child = child[0];
						var child_parent = $(ui.draggable.parent().parent()).attr('id');
						if(child_parent){child_parent = child_parent.substr(13).split(':');child_parent = child_parent[0];}
						if (child && parent != child_parent) {
							ui.draggable.fadeOut('slow',function(){ui.draggable.remove()});
							Notification.loader('div#topmenu .top','small');
							Lang.FadeOut();
							$.post(URL_MOVE, "child="+child+"&parent="+parent, function(theResponse){
								Lang.FadeIn();
								$('.m').html(theResponse);
								Page.SetMyTooltip();
								Notification.removeLoader('div#topmenu .top','small');
							});
		
						}
					}else{
						Notification.alert(LangJs['_YOU_CANT_MOVE_SELECTED_CATEGORY_TO_THIS_PARENT']);
					}
				}
			}
		);
		$('div.cat_2,div.cat').draggable({
			revert		: true,
			gHost		: true,
			handle		: 'span.move',
			zIndex		: 1000,
			start		: function(){$('.main_button').fadeTo('slow',1);},
			stop		: function(){$('.main_button').fadeTo('slow',0.1);}
		});
	},
	MoveMenu: function(){
		$(".menu-list").sortable({ opacity: 0.6, cursor: 'move',handle: '.move',  update: function() {
				var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_MENU_MOVE_MENU, data, function(theResponse){
					$('body').prepend(theResponse);
					Notification.removeLoader('div#topmenu .top','small');
					Lang.FadeIn();
				}); 															 
			}								  
		});
	},
	DestroyMove: function(){
		$('div.cat_2,div.cat').draggable("destroy");
		$('div.parent,div.child').droppable("destroy");
	},
	DestroyPosition: function(){
		$("div.sortable").sortable("destroy");
	},
	ChangeMode: function(value){
		$.cookie('menu-mode',value);
		Menu.SetMode();
	},
	SetMode: function(){
		if($.cookie('menu-mode') != 2){
			$('#mode-move').removeClass('active');
			$('.main_button').slideUp('slow').fadeOut('slow');
			Menu.DestroyMove();
			Menu.Position();
			$('#mode-position').addClass('active');
		}else{
			$('#mode-position').removeClass('active');
			$('.main_button').slideDown('slow').fadeTo('slow',0.1);
			Menu.DestroyPosition();
			Menu.Move();
			$('#mode-move').addClass('active');
		}
		Menu.LoadModeFunction();
	},
	ChangeMenuInList: function(id,value){
		Page.RemoveFloatBox();
		Notification.loader('div#topmenu .top','small');
		Lang.FadeOut();
		$.post(URL_CHANGE_MENU, "id="+id+"&value="+value, function(theResponse){
				Lang.FadeIn();
				$('.m').html(theResponse);
				Page.SetMyTooltip();
				Notification.removeLoader('div#topmenu .top','small');
		});
	},
	ChangeMenu: function(el){
		Notification.loader();
		$.cookie('id_sm_menu',$(el).val());
		$('#submit').val('');
		Lang.SetSubmit();
		$('input[type=submit]').trigger('click');
	},
	/*for a categories list*/
	ShowFormMenu: function(id,el,json){
			if(id && json){
				var html = '<ul class="change-menu">';
				var selected = json.selected;
				$.each(json,function(index,value){
					if(index != 'selected'){
						value = value.split('::');
						html += '<li '+((index == selected)?'class="active"':'onclick="Menu.ChangeMenuInList(\''+id+'\',\''+index+'\')"')+' ><span class="change-'+value[1]+'"></span><small>'+value[0]+'</small></li>'; 
					}
				});
				html += '</ul>';
				Page.ShowFloatBox(html,el,'160px','auto',id);
				$('ul.change-menu li').mouseover(function(){$('ul.change-menu li').removeClass('hover');if(!$(this).hasClass('active'))$(this).addClass('hover');});
				$('ul.change-menu li').mouseout(function(){$(this).removeClass('hover');});
			}else{Notification.alert(LangJs['_UNEXPECTED_ERROR']);}
	},
	LoadModeFunction: function(){
		if($.cookie('menu-mode') != 2){$('.m .mode').removeClass('move');$('.m .mode').addClass('position');}
		else{$('.m .mode').removeClass('position');$('.m .mode').addClass('move');}
	},
	
	ChangeStatus: function(id,val){
		Notification.loader('div#topmenu .top','small');
		Lang.FadeOut();
		$.post(URL_MENU_CHANGE_STATUS, "id="+id+"&value="+val, function(theResponse){
			if(val == 2){$('.tr_'+id).addClass('tr_red');}
			else{$('.tr_'+id).removeClass('tr_red');}
			Lang.FadeIn();
			Notification.removeLoader('div#topmenu .top','small');
		});
	},
	/*change icon menu type*/
	ChangeVisibleType: function(el){
		if($(el).val()){
			if($(el).next('.menu-type').css('display') == 'none'){$(el).next('.menu-type').fadeIn('fast');}
			$(el).next('.menu-type').attr('class','menu-type menu-type-'+$(el).val());
		}else{$(el).next('.menu-type').fadeOut('fast');}
	},
	/*tabs function*/
	SetTabs: function(el){
		var self = this;
		$(el+' #mt_'+$.cookie('id_sm_menu')).addClass('active');
		$(el+' li').bind({
			'mouseover': function(){
				$(el+' li').removeClass('hover');
				$(this).addClass('hover');
			},
			'mouseout': function(){
				$(this).removeClass('hover');
			},
			'click': function(){
				if(!$(this).children('a').length){
					$.cookie('id_sm_menu',$(this).attr('id').replace('mt_',''));
					$(el+' li').removeClass('active');
					$(el+' #mt_'+$.cookie('id_sm_menu')).addClass('active');
					Lang.SetLang($.cookie('lang'),'list',true);
				}
			}
		});
	}
};



function float(el){
	var float=/^[0-9\.]*$/i;
	var not_float=/[^0-9\.]+/g;
	var value = $(el).val();
	if(value.match(float)){$(el).val(value);
	}else{$(el).val(value.replace(not_float,""));}
}

function integer(el){
	var format=/^[0-9]*$/i;
	var not_format=/[^0-9]+/g;
	var value = $(el).val();
	if(value.match(format)){$(el).val(value);
	}else{$(el).val(value.replace(not_format,""));}
}

function isInteger(s) {
  return (s.toString().search(/^-?[0-9]+$/) == 0);
}



var Categories = {
	SetLang: function(URL_LANG,el,value,lang){
		if(el){
		var data = "id="+el+"&value="+value+'&lang='+lang;
			notice_load();
			$.post(URL_LANG, data, function(theResponse){remove_notice_load()}); 		
		}
	},
	Show: function(id){
		$('.child[id!="child_'+id+'"]').slideUp('fast');
		$('.li_parent > a').removeAttr('class');
		$('#parent_'+id).attr('class','active');
		$('#child_'+id).slideToggle('fast');
	},
	ChangeUrl: function(el){
		if($(el).val()){
			$('#url').val('').attr('disabled',true);
		}else{$('#url').attr('disabled',false);}
	}
};

var Articles = {
	Move: function(id){
		$("#articles_list").sortable({ opacity: 0.6, cursor: 'move',items: 'div',  update: function() {}});
	},
	AddArticles: function(el,box){
		var id = $('#'+el+' :selected').val();
		var title = $('#'+el+' :selected').text();
		var exist = 0;
		if(id){
			$('.articles_list').each(function(){
				if($(this).val() == id){
					alert(LangJs['_SELECTED_ARTICLE_IS_ALREADY_ADDED']+'.');
					exist = 1;
				}
			});
			if(!exist){
				$('#'+box).append('<div id="articles_'+id+'" ><input type="hidden" name="articles_list[]" class="articles_list" id="articles_list_'+id+'" value="'+id+'" /><span>'+title+'</span><a id="delete_'+id+'" class="delete" href="javascript:Articles.DeleteArticles(\''+id+'\')">&nbsp;</a><span class="clear">&nbsp;</span></div>');
				Articles.Move();
			}
		}else{alert(LangJs['_ARTICLE_WAS_NOT_SELECTED']+'.');}
	
	},
	DeleteArticles: function(id){
		$('#articles_'+id).remove();
	},
	ChangeAccess: function(id,value){
		if(id){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$.post(URL_ARTICLE_CHANGE_ACCESS, "id="+id+"&value="+value, function(theResponse){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success == true){$('.access-'+id).val(value);
				}else if(theResponse.error){Notification.error(theResponse.error);}
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}); 		
		}
	},
	ChangeStatus: function(id,value){
		if(id){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$.post(URL_ARTICLE_CHANGE_STATUS, "id="+id+"&value="+value, function(theResponse){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success == true){
					$('.status-'+id).val(value);
					if(value != 1){$('.tr_'+id).addClass('tr_red');
					}else{$('.tr_'+id).removeClass('tr_red');}
				}else if(theResponse.error){Notification.error(theResponse.error);}
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}); 		
		}
	},
	ChangeHomePage: function(id){
		if(id){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$('.home-page').attr('checked',false);
			$('.home-page-'+id).attr('checked',true);
			$('.tr_green').removeClass('tr_green');
			$('.tr_'+id).addClass('tr_green');
			$.post(URL_ARTICLE_CHANGE_HOME_PAGE, "id="+id, function(theResponse){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success == true){
				}else if(theResponse.error){Notification.error(theResponse.error);}
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}); 		
		}
	},
	ChangeDefaultGroup: function(id){
		if(id){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$('.default-group').attr('checked',false);
			$('.default-group-'+id).attr('checked',true);
			$('.tr_green').removeClass('tr_green');
			$('.tr_'+id).addClass('tr_green');
			$.post(URL_CHANGE_ARTICLE_GROUP, "id="+id, function(theResponse){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success == true){
				}else if(theResponse.error){Notification.error(theResponse.error);}
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}); 		
		}
	},
	/*Change Articles Group*/
	ChangeGroup: function(id){
		if(id){
			Notification.loader();
			$.cookie('id_sm_articles_group',id);
			$('#submit').val('');
			Lang.SetSubmit();
			$('input[type=submit]').trigger('click');
		}
	}
};
/* Components object */
var ArticleComponents = {
	Move: function(id){
		$("#components_list").sortable({ opacity: 0.6, cursor: 'move',items: 'div',  update: function() {}});
	},
	AddComponents: function(el,el_type,box){
		var id = $('#'+el+' :selected').val();
		var title = $('#'+el+' :selected').text();
		var id_type = $('#'+el_type+' :selected').val();
		var title_type = $('#'+el_type+' :selected').text();
		var exist = 0;
		if(id){
			$('.components_list').each(function(){
				if($(this).val() == id){
					Notification.alert(LangJs['_SELECTED_COMPONENT_IS_ALREADY_ADDED']+'.');
					exist = 1;
				}
			});
			if(!exist){
				$('#'+box).append('<div id="components_'+id+'" >'
				+'<input type="hidden" name="components_list[]" class="components_list" id="components_list_'+id+'" value="'+id+'" />'
				+'<input type="hidden" name="components_list_type['+id+']" class="components_list_type" id="components_list_type_'+id+'" value="'+id_type+'" />'
				+'<span>'+title+'|'+title_type+'</span>'
				+'<a id="delete_'+id+'" class="delete" href="javascript:ArticleComponents.DeleteComponents(\''+id+'\')">&nbsp;</a><span class="clear">&nbsp;</span></div>');
				ArticleComponents.Move();
			}
		}else{Notification.alert(LangJs['_COMPONENT_WAS_NOT_SELECTED']+'.');}
	
	},
	DeleteComponents: function(id){$('#components_'+id).remove();}
};




var News = {
	ChangeStatus: function(id,value){
		if(id){
			var data = "id="+id+"&value="+value;
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			if(value == '1'){ $('.item-'+id).removeClass('tr_red');$('.news-status-'+id).val('1');
			}else{$('.item-'+id).addClass('tr_red');$('.news-status-'+id).val('2');}
			$.post(URL_NEWS_CHANGE_STATUS, data, function(theResponse){
				$('body').prepend(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 		
		}
	},
	AddHotNews: function (URL_NEWS,id,value){
		if(id && URL_NEWS){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			if(value == '1'){ $('.hot_news_'+id).val('0');$('.hot_news_'+id).attr('checked',true);
			}else{$('.hot_news_'+id).val('1');$('.hot_news_'+id).attr('checked',false);}
			data = "id="+id+"&value="+value;
			$.post(URL_NEWS, data, function(theResponse){
				$('#hotnews').html(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 	
		
		}
	},
	Move: function(){
		$("#hotnews").sortable({ opacity: 0.6, cursor: 'move',handle: 'span.move',  update: function() {
				var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_NEWS_MOVE, data, function(theResponse){
					$('body').prepend(theResponse);
					Notification.removeLoader('div#topmenu .top','small');
					Lang.FadeIn();
				}); 															 
			}								  
		});
	}
};


var Banner = {
	ChangeStatus: function(id,value){
		if(id){
			var data = "id="+id+"&value="+value;
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			if(value == '1'){ $('.item-'+id).removeClass('tr_red');$('.banner-status-'+id).val('1');
			}else{$('.item-'+id).addClass('tr_red');$('.banner-status-'+id).val('2');}
			$.post(URL_BANNER_CHANGE_STATUS, data, function(theResponse){
				$('body').prepend(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 		
		}
	},
	Move: function(){
		$(".banner-list").sortable({ opacity: 0.6, cursor: 'move',handle: '.move',  update: function() {
				var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_BANNER_MOVE, data, function(theResponse){
					$('body').prepend(theResponse);
					Notification.removeLoader('div#topmenu .top','small');
					Lang.FadeIn();
				}); 															 
			}								  
		});
	},
	SetAccordion: function(el){
		Banner.SetAnimate(el);
		var t = setInterval("Banner.SetAnimate('"+el+"')",6000);
		$(el+' > li').hover(
				function(){
					Banner.CloseActive($(el+' > li.active:not(#'+$(this).attr('id')+')'));
            		Banner.Animate(this);
            		clearInterval(t);
				},
				function(){
           			//Banner.CloseActive(this);
           			t = setInterval("Banner.SetAnimate('"+el+"')",6000);
				}
		);
	},
	SetAnimate: function(el){
		var active = $(el+' > li.active');
		var next = (!active.length || !$(active).prev().length)?$(el+' li:last'):$(active).prev();
		$(el+' > li').removeClass('active');
		if($(active).attr('id') != $(next).attr('id')){
			this.CloseActive(active);
			this.Animate(next);
		}
	}, 
	
	Animate: function(el){
		if(!$(el).hasClass('active') || $(el).width() < '380'){
			$(el).stop().animate({'width':'383px'},500,function(){});
			$('#h-'+$(el).attr('id')).fadeIn();
			$(el).addClass('active');
		}else{}
	},
	CloseActive: function(active){
		$(active).stop().animate({'width':'99px'},1000,function(){$(active).removeClass('active');});
		$(active).each(function(){
			$('#h-'+$(this).attr('id')).fadeOut();
		});
	}
};


var Slider = {
	NormalSlide: function(el,child,time){
		if($(el+' '+child).length > 1){
		 var $active = $(el+' .active');
    	 if($active.length == 0) $active = $(el+' '+child+':first');
    	 var $next =  $active.next().length ? $active.next() : $(el+' '+child+':first');
    	$active.addClass('last-active');
    	$active.animate({opacity: 0.0}, time, function() {
    		$active.css('display','none');
    		$next.css({opacity: 0.0,display: 'block'})
       			.addClass('active')
        		.animate({opacity: 1.0}, time, function() {
     	       		$active.removeClass('active last-active');
    			});
    		});
   		}
	}
};


var Partner = {
	ChangeStatus: function(id,value){
		if(id){
			var data = "id="+id+"&value="+value;
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			if(value == '1'){ $('.item-'+id).removeClass('tr_red');$('.partner-status-'+id).val('1');
			}else{$('.item-'+id).addClass('tr_red');$('.partner-status-'+id).val('2');}
			$.post(URL_PARTNER_CHANGE_STATUS, data, function(theResponse){
				$('body').prepend(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 		
		}
	},
	Move: function(){
		$(".partner-list").sortable({ opacity: 0.6, cursor: 'move',handle: '.move',  update: function() {
				var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_PARTNER_MOVE, data, function(theResponse){
					$('body').prepend(theResponse);
					Notification.removeLoader('div#topmenu .top','small');
					Lang.FadeIn();
				}); 															 
			}								  
		});
	}
};


var Newsletter = {
	SetEvents: function(){
		$('.e-check').live('change',function(){
			if($(this).attr('checked') != true){$(this).parents('div:eq(0)').removeClass('checked');
			}else{$(this).parents('div:eq(0)').addClass('checked');}
		});
		$('#check-all').click(function(){
			if($(this).attr('checked') != true){
				$('.e-check').attr('checked',false);
				$('.n-item').removeClass('checked');
			}else{
				$('.e-check').attr('checked',true);
				$('.n-item').addClass('checked');
			}
		});
		$('#check-lang').change(function(){
			if($(this).val()){
				$('.e-check-lang-'+$(this).val()).attr('checked',true);
				$('.e-check-lang-'+$(this).val()).parent().parent().addClass('checked');
			}else{
				$('.e-check').attr('checked',false);
				$('.e-check').parent().parent().removeClass('checked');
			}
		});
		$('#check-group').change(function(){
			if($(this).val()){
				$('.e-check-group-'+$(this).val()).attr('checked',true);
				$('.e-check-group-'+$(this).val()).parent().parent().addClass('checked');
			}else{
				$('.e-check').attr('checked',false);
				$('.e-check').parent().parent().removeClass('checked');
			}
		});
		
	}
};

var Groups = {
	SetModule: function(el){
		if($(el).attr('checked') == true){
			$(el).parent().addClass('checked');
			$('.'+$(el).val()).parent().addClass('checked');
			$('.'+$(el).val()).attr('checked',true);
		}else{
			$(el).parent().removeClass('checked');
			$('.'+$(el).val()).parent().removeClass('checked');
			$('.'+$(el).val()).attr('checked',false);
		}
	},
	SetAction: function(el,parent){
		if($(el).attr('checked') == true){
			$(el).parent().addClass('checked');	
			$('#'+parent).attr('checked',true);
			$('#'+parent).parent().addClass('checked');	
		}else{
			$(el).parent().removeClass('checked');
			if(!$('.'+parent+':checked').length){
				$('#'+parent).attr('checked',false);
				$('#'+parent).parent().removeClass('checked');
			}
		}
	}
};

var Page = {
	SetClosedBox: function(){
		var self = this;
		$('.closed-box .toolbar-box').bind({
			'click': function(){
				if($.cookie('closed-box-'+$(this).parent().attr('id'))){
					self.OpenBoxClosed(this);
				}else{self.CloseBoxClosed(this);}
			},
			'mouseover': function(){},
			'mouseout': function(){}
		});
		$('.closed-box .toolbar-box').each(function(){
			if($.cookie('closed-box-'+$(this).parent().attr('id'))){
				self.CloseBoxClosed(this);
			}else{self.OpenBoxClosed(this);}
		});
	},
	CloseBoxClosed: function(el){
		$(el).addClass('closed');
		$(el).next().hide();
		$.cookie('closed-box-'+$(el).parent().attr('id'),'closed');
	},
	OpenBoxClosed: function(el){
		$(el).removeClass('closed');
		$(el).next().show();
		$.cookie('closed-box-'+$(el).parent().attr('id'),'');
	},
	FooterPosition: function(){
		var body_height = $('body').height();
		var wrapper_height = $('#content').height();
		if(body_height-wrapper_height>50){
			$('body').css('position','relative');
			$('#footer').css('position','absolute');
		}else{
			$('body').css('position','static');
			$('#footer').css('position','static');
		}
	},
	SetBoxSize: function(){
		var height = 0;
		$('.content-box').each(function(){
			 if(height < $(this).height()){height = $(this).height();}
		});
		$('.content-box').css('height',height+'px');
	},
	CheckWindowHeight: function(){
		$(window).resize(function(){
			Page.FooterPosition();
		});
		$('.content-box').bind("DOMSubtreeModified",function(){
			//TODO:zlikwidowac efekt stroboskopu.
			Page.FooterPosition();
		});
	},
	SetBorderForInput: function(){
		$('input').filter(function(){if($(this).hasClass('error-field') || $(this).hasClass('no-border')) return false;else return true;}).focus(function(){$(this).addClass('backlight')});
		$('input').filter(function(){if($(this).hasClass('error-field') || $(this).hasClass('no-border')) return false;else return true;}).blur(function(){$(this).removeClass('backlight')});
		$('textarea').filter(function(){if($(this).hasClass('error-field') || $(this).hasClass('no-border')) return false;else return true;}).focus(function(){$(this).addClass('backlight')});
		$('textarea').filter(function(){if($(this).hasClass('error-field') || $(this).hasClass('no-border')) return false;else return true;}).blur(function(){$(this).removeClass('backlight')});
		$('select').filter(function(){if($(this).hasClass('error-field') || $(this).hasClass('no-border')) return false;else return true;}).focus(function(){$(this).addClass('backlight')});
		$('select').filter(function(){if($(this).hasClass('error-field') || $(this).hasClass('no-border')) return false;else return true;}).blur(function(){$(this).removeClass('backlight')});
	},
	SetMyTooltip: function(){
		$('*[title]:not(option)').mytooltip({ 
    		delay: 0, 
    		showURL: false, 
    		showBody: " - ", 
    		fade: 50
		});
	},
	SetLightbox: function(type){
		if(type == 'fast'){
			$('a[rel*=lightbox]').lightBox({containerResizeSpeed: 50});
		}else{
			$('a[rel*=lightbox]').lightBox();
		}
	},
	FloatBox: null,
	ShowFloatBox: function(html,el,width,height,id){
		if(Page.FloatBox != id){
			$('body').append('<div class="float-box"><div class="float-first"></div><div class="float-second">'+html+'</div></div>');
			$('.float-box').css({'height':height, 'width':width});
			$('.float-box').css({
				'top' 	:($(el).offset().top+$(el).outerHeight()/2)+'px',
				'left'  :($(el).offset().left+($(el).outerWidth()/2)-$(".float-first").outerWidth()/2)+'px'
			});
			$(document).click(function(){Page.RemoveFloatBox();});
 			$('.type a').click(function(e){ e.stopPropagation(); });
 			$('.float-box').click(function(e){ e.stopPropagation(); });
 			Page.FloatBox = id;
 		}else{Page.RemoveFloatBox();}
	},
	RemoveFloatBox: function(){$('.float-box').remove();Page.FloatBox = null;
	},
	Window: function(url, height, width){
		return window.open(url,"preview-template","width="+width+", height="+height);
	}
	
};

var Panel = {
	SetMenuLeft: function(){
		$("ul#leftmenu li span").click(function(){
			if($(this).next().css('display') != 'block'){
				$('ul#leftmenu li ul').slideUp(100);
				$(this).next().slideDown(100);
			}else{
				$(this).next().slideUp(100);
			}
			return false;
		});
		$('ul#leftmenu li span, a.a_main').bind({
			'mouseover':function(){$(this).stop().animate({paddingRight:'25px'},200);},
			'mouseout': function(){$(this).stop().animate({paddingRight:'15px'},200);}
		});
	}
};

/*spliter for editor*/
var Splitter = {
	Instance: null,
	Set: function(el){
		$(el).splitter({
			type: "v",
			outline: true,
			minLeft: 100, sizeLeft: '50%', minRight: 100,
			resizeToWidth: true,
			cookie: "vsplitter",
			accessKey: 'I'
		});
		this.Instance = $(el);
	},
	Destroy: function(){
		if(this.Instance){$(this.Instance).trigger('destroy');}
	},
	Restore: function(el){
		if($(el+' #RightPane').css('display') != 'none'){
			Splitter.Destroy();
			Splitter.Set(el);
		}
	}
	
};


/*Template components class*/
var TComponents = {
	DefineChangeType: function(el){
		var self = this;
		$(el).bind('change',function(){self.SetType($(this).val());});
		(!$('#new').is(':checked'))?self.HideBox():null;
		
		$('#new').bind('change',function(){($(this).attr('checked'))?self.ShowBox():self.HideBox();});
  		self.SetType($('#type').val());
	},
	ShowBox: function(){$('.two-box').slideDown('fast',function(){TComponents.SetType($('#type').val());});},
	HideBox: function(){$('.two-box').slideUp('fast');},
	SetType: function(v){
		if(v!= COMPONENT_TYPE && v!= COMPONENT_TYPE_2){
			$('.path').show();
			$('.name').hide();$('#name').val('');
			if(v == 1 || v == 2 || v == 5) var id = 'html';
			if(v == 3) var id = 'css';
			if(v == 4) var id = 'js';
			$('.two-box #LeftPane h2 .text').text(LangJs['_INPUT_'+id.toUpperCase()+'_CODE']);
			if($('.two-box').is(":visible")){Splitter.Destroy()};
			EditorSyntax.Destroy();
			$('.two-box #RightPane').hide();
			$('.two-box #LeftPane .editor textarea').attr('id',id);
			EditorSyntax.SetAll();
		}else{
			$('.name').show();
			$('.path').hide(); $('#path').val('');
			$('.two-box #LeftPane h2 .text').text(LangJs['_INPUT_PHP_CODE']);
			$('.two-box #RightPane').show();
			Splitter.Set('.two-box');
			EditorSyntax.Destroy();
			$('.two-box #LeftPane .editor textarea').attr('id','php');
			EditorSyntax.SetAll();
		}
	},
	ChangeStatus: function(id,value){
		if(id){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$.post(URL_COMPONENTS_CHANGE_STATUS, "id="+id+"&value="+value, function(theResponse){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success == true){
					$('.status-'+id).val(value);
					if(value != 1){$('.tr_'+id).addClass('tr_red');
					}else{$('.tr_'+id).removeClass('tr_red');}
				}else if(theResponse.error){Notification.error(theResponse.error);}
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}); 		
		}
	}
};


var ComponentsEditor = {
	SetScrollTop: function(){
		if($(window).height() > $('.content-box-left').height()+$('.content-box-left').offset().top){
			$(window).scroll(function(data){
			 	var difference = 60;
			 	var margin_top = $(document).scrollTop();
			 	if(margin_top < difference) margin_top = difference;
			 	$('.content-box-left').animate({marginTop:margin_top-difference},100);
			});
		}
	},
	TimeOut: undefined,
	DefineSearch: function(el,el_s){
		var self = this;
		$(el).val($.cookie('editor-search'));
		self.Search(el,el_s);
		$(el).bind('keyup',function(){
			if(self.TimeOut != undefined){clearTimeout(self.TimeOut);}
			self.TimeOut = setTimeout(function(){self.Search(el,el_s);}, 200);
		});
	},
	Search: function(el,el_s){
		Notification.loader('div#topmenu .top','small');
		$.post(URL_EDITOR_SEARCH_COMPONENTS, "word="+$(el).val(), function(theResponse){
			$(el_s).html(theResponse);
			Notification.removeLoader('div#topmenu .top','small');
		});
		Splitter.Restore('#two-box');
		$.cookie('editor-search',$(el).val());
	},
	
	DefineEvents: function(el){
		var self = this;
		$.cookie('editor-full-screen','');
		if(!el) el = '.files';
		$(el+' .close').bind({
			'mouseover': function(){$(this).addClass('close-hover');},
			'mouseout': function(){$(this).removeClass('close-hover');},
			'click': function(){self.CloseFile($(this).parent().attr('id').replace('f-n-',''));}
		});
		$(el).bind({
			'mouseover': function(){$(this).addClass('file-hover');},
			'mouseout': function(){$(this).removeClass('file-hover');},
			'click': function(){
				$(this).removeClass('file-hover');
				$('.files').removeClass('file-active');
				$(this).addClass('file-active');
				self.LoadFile($(this).attr('id').replace('f-n-',''));
			},
			'dblclick': function(){
				if(!$.cookie('editor-full-screen')) self.Maximize();
				else self.Minimize();
				Splitter.Restore('#two-box');
			}
		});
	},
	AddToEditor: function(id,path,type){
		if(!CookieJson.Get('editor-files',id)){
			CookieJson.Add('editor-files',id,{'id':id,'path':path,'type':type});
			this.OpenFile(id,path,type);
		}else{this.ShowFile(id);}
		this.SetCurrentFile(id);
		
	},
	CheckOpen: function(id,items){
		var exist = 0;
		$.each(items,function(k,v){if(k==id){exist = 1;return false;}});
		return (exist)?true:false;
	},
	OpenFile: function(id,path,type){
	 	this.AddFileToNavigation(id,path,type);
	 	this.LoadFile(id,path,type);
	},
	CloseFile: function(id){
		var changed = null;
		if(changed = CookieJson.Get('editor-changed',id)){
			var file = CookieJson.Get('editor-files',id);
			var r = confirm("'"+PHP.basename(file.path)+"' "+LangJs['_HAS_BEEN_MODIFIED_CLOSE_FILE']);
		}
		if(r || !changed){
			this.RemoveFileFromNavigation(id);
			file = CookieJson.Get('editor-files',id);
			CookieJson.Remove('editor-files',id);
			CookieJson.Remove('editor-changed',id);
			$('#f-'+id).remove();
			$('#f2-'+id).remove();
			if($.cookie('editor-current') == id){
				var previous = $.cookie('editor-previous');
				if(CookieJson.Get('editor-files',previous)){
					this.SetCurrentFile(previous);
					this.ShowFile(previous,false,file);	
				}else{
					EditorSyntax.Destroy();
					$('.content').val('');
					$('.content2').val('');	
				}
			}
		}
	},
	SetCurrentFile: function(id){
		$('.files').removeClass('file-active');
		$('#f-n-'+id).addClass('file-active');
	},
	AddFileToNavigation: function(id, path, type){
		$('.editor-navigation .scroll-box').append('<div class="files" id="f-n-'+id+'"><span onselectstart="return false;" title="'+path+'"><b> &nbsp; </b>'+PHP.basename(path)+'</span><span class="close">&nbsp;</span></div>');	
		this.DefineEvents('#f-n-'+id);
		this.CheckNavigationSize();
		Page.SetMyTooltip();
	},
	CheckNavigationSize: function(){
		var box_width = $('.editor-navigation .scroll').width();
		var width = 0;
		$('.editor-navigation .scroll .scroll-box').children('.files').each(function(){
			width+= $(this).outerWidth(true);
		});
		if(this.ScrollNavigation){$('.editor-navigation .scroll-box').width(width);}
		if(box_width<width && !this.ScrollNavigation){this.AddScrollingNavigation(width);}
		if(box_width>width &&  this.ScrollNavigation){this.RemoveScrollingNavigation();}
	},
	ScrollNavigation: null,
	AddScrollingNavigation: function(width){
		var self = this;
		self.ScrollNavigation = true;
		$('.editor-navigation .scroll-box').width(width);
		$('.editor-navigation .scroll-left').show();
		$('.editor-navigation .scroll-right').show();
		$('.editor-navigation').css({'margin-left':'0px','margin-right':'0px'});
		$('.editor-navigation .scroll').css('margin','0px 12px 0px 11px');
		$('.editor-navigation .scroll-left').bind({
			'mouseover': function(){$(this).css('background-color','#999');},
			'mouseout': function(){$(this).css('background-color','#ccc');},
			'click': function(){self.NavigationMove(-1,100);}
		});
		$('.editor-navigation .scroll-right').bind({
			'mouseover': function(){$(this).css('background-color','#999');},
			'mouseout': function(){$(this).css('background-color','#ccc');},
			'click':function(){self.NavigationMove(1,100);}
		});
		self.NavigationMove(0);
	},
	RemoveScrollingNavigation: function(){
		this.ScrollNavigation = null;
		$.cookie('navigation-position',0);
		$('.editor-navigation .scroll-left').hide();
		$('.editor-navigation .scroll-right').hide();
		$('.editor-navigation .scroll-box').animate({'margin-left':'0px'},0);
		$('.editor-navigation .scroll-box').css('width','auto');
		$('.editor-navigation .scroll').css('margin','0px');
		$('.editor-navigation .scroll-left').unbind('mouseover mouseout click');
		$('.editor-navigation .scroll-right').unbind('mouseover mouseout click');
		
	},
	NavigationMove: function(val,duration){
		var position = parseInt($.cookie('navigation-position'));
		var new_position = ((position+val)>0)?(position+val):0;
		var margin = 0, i = 0, width = 0, width_box = $('.editor-navigation .scroll').width();
		$('.editor-navigation .scroll .scroll-box').children('.files').each(function(){
			i++;
			if(new_position>=i){margin += $(this).outerWidth(true);}
			width += $(this).outerWidth(true);
		});
		if(width_box <= (width+parseInt($('.editor-navigation .scroll-box').css('margin-left'))) || val < 0){
			$('.editor-navigation .scroll-box').animate({'margin-left':-margin+'px'},(duration)?duration:0);
			$.cookie('navigation-position',new_position);
		}
	
	},
	RemoveFileFromNavigation: function(id){
		$('#f-n-'+id).remove();
		this.CheckNavigationSize();
	},
	/*load file from php*/
	LoadFile: function(id){
		var self = this;
		if($('#f-'+id).length){
			self.ShowFile(id);
		}else{
			Notification.loader('div#topmenu .top','small');
			$('.two-box .editor').fadeTo('fast',0.2);
			$.post(URL_EDITOR_LOAD_FILE, "id="+id, function(jsonResponse){
				if(jsonResponse){
					jsonResponse = JSON.parse(jsonResponse);
					if(jsonResponse.error){
						Notification.error(jsonResponse.error);
						self.CloseFile(id);
						if(t){clearTimeout(t);}
						var t = setTimeout("Notification.removeAllSlow()",5000);
					}else{
						$('.file-repository').append('<input type="hidden" id="f-'+id+'" value="'+jsonResponse.content+'" />');
						$('.file-repository').append('<input type="hidden" id="f2-'+id+'" value="'+jsonResponse.content2+'" />');
						self.ShowFile(id);
					}
				}	
				$('.two-box .editor').fadeTo('fast',1);
				Notification.removeLoader('div#topmenu .top','small');
			});
		}
	},
	/*method for save content to a file*/
	SaveFile: function(){
		this.SetFileChange();
		var id = $.cookie('editor-current');
		var file = CookieJson.Get('editor-files',id);
		if(file && CookieJson.Get('editor-changed',id)){
			var content = $('#f-'+id).val();
			var content2 = $('#f2-'+id).val();
			Notification.loader('div#topmenu .top','small');
			$('.two-box .editor').fadeTo('fast',0.2);
			$.post(URL_EDITOR_SAVE_FILE, { "id" : id, "type" : file.type, "path" : file.path, "content" : content, "content2" :content2}, function(jsonResponse){
				jsonResponse = JSON.parse(jsonResponse);
				if(jsonResponse.success){
					CookieJson.Remove('editor-changed',id);
					$('#f-n-'+id+' span:first b').html('&nbsp;');
				}
				$('.two-box .editor').fadeTo('fast',1);
				Notification.removeLoader('div#topmenu .top','small');
			});
		} 
	},
	/*method add content to editor*/
	ShowFile: function(id,reload,file){
		var item = CookieJson.Get('editor-files',id),current_id = $.cookie('editor-current'), type = '';
		if(current_id && !file){
			if(current_id == id && !reload){return false;}
			current = CookieJson.Get('editor-files',current_id);
			if(current){type = (current)?current.type:'';}
		}else if(file){ //for return to previous file
			current_id = file.id;
			type = file.type;
		}
		if(item){
			var code = $('#f-'+id).val(), code2 = $('#f2-'+id).val();
			if(item.type == type && !reload){
				this.SelectAnotherFile = 1;
				if(item.type == 1 || item.type == 2 || item.type == 5) EditorSyntax.EditorHtml.setCode(code);
				if(item.type == 3) EditorSyntax.EditorCss.setCode(code);
				if(item.type == 4) EditorSyntax.EditorJs.setCode(code);
				if(item.type == 6 || item.type == 7){
					this.SelectAnotherFile = 2;
					EditorSyntax.EditorPhp.setCode(code);
					(code2)?EditorSyntax.EditorHtml.setCode(code2):null;
				}
			}else{
				EditorSyntax.Destroy();
				if(item.type != 6 && item.type != 7){
					Splitter.Destroy();
					$('.two-box #RightPane').hide();
					$('.content2').removeAttr('id');
				}else{
					Splitter.Set('.two-box');
					$('.two-box #RightPane').show();
					$('.content2').attr('id','html');
				}
				$('.content').val(code);
				$('.content2').val(code2);
				if(item.type == 1 || item.type == 2 || item.type == 5){ el_id = 'html';}
				if(item.type == 3){ el_id = 'css' }
				if(item.type == 4){ el_id = 'js';}
				if(item.type == 6 || item.type == 7){ el_id = 'php';}
				$('.content').attr('id',el_id);
				$('.two-box #LeftPane h2 .text').text(LangJs['_INPUT_'+el_id.toUpperCase()+'_CODE']);
				EditorSyntax.SetAll(function(){ComponentsEditor.SetFileChange();});
			}
		}
		$.cookie('editor-previous',current_id);
		$.cookie('editor-current',id);
	},
	Current: function(){
		$.cookie('editor-changed',''); //set change clear for a start
		if(id = $.cookie('editor-current')){
			this.SetCurrentFile(id);
			this.ShowFile(id,true);
		}
	},
	SelectAnotherFile: 0, //for file change
	SetFileChange: function(){
		var id = $.cookie('editor-current');
		if(id && !ComponentsEditor.SelectAnotherFile){
			$('#f-n-'+id+' span:first b').html('*');
			CookieJson.Add('editor-changed',id,1);
			this.SaveChangesToHtml(id);
		}else if(ComponentsEditor.SelectAnotherFile){ComponentsEditor.SelectAnotherFile -=1;}
	},
	SaveChangesToHtml: function(id){
		var file = CookieJson.Get('editor-files',id);
		if(file){
			var code = '',code2 = '';
			if(file.type == 1 || file.type == 2 || file.type == 5) code = EditorSyntax.EditorHtml.getCode();
			if(file.type == 3) code = EditorSyntax.EditorCss.getCode();
			if(file.type == 4) code = EditorSyntax.EditorJs.getCode();
			if(file.type == 6 || file.type == 7){code = EditorSyntax.EditorPhp.getCode();code2 = EditorSyntax.EditorHtml.getCode();}
			$('#f-'+id).val(code);
			$('#f2-'+id).val(code2);
		}
	},
	
	Maximize: function(){
		$('body').css({'background': '#F0F0F0'});
		$('#content').css({
			'position': 'relative',
			'z-index': '2',
			'margin-left':'0px',
			'height':'100%'
		});
		$('.content-right').hide();
		$('.content-box-left').css({'margin-right': '0px'});
		$.cookie('editor-full-screen',1);
	},
	Minimize: function(){
		$('body').css({'background': 'url("public/graf/admin/bg-body.gif") repeat-y left top #F0F0F0'});
		$('#content').css({
			'position': 'static',
			'z-index': 'auto',
			'margin-left':'230px',
			'height':'auto'
		});
		$('.content-right').show();
		$('.content-box-left').css({'margin-right': '300px'});
		$.cookie('editor-full-screen','');
	}
};


var CookieJson = {
	Add: function(name, field, val){
		if(name){
			var cookie = $.cookie(name);
			var items = (cookie)?JSON.parse(cookie):{};
			items[field] = val;
			$.cookie(name,JSON.stringify(items));
		}	
	},
	Get: function(name,field){
		if(name){
			var cookie = $.cookie(name);
			var items = cookie?JSON.parse(cookie):{};
			return (field)?items[field]:items;
		}
	},
	Set: function(name,value){
		if(name){$.cookie(name,value);}
	},
	Remove: function(name,id){
		if(name){
			var cookie = $.cookie(name);
			if(cookie){
				var items = JSON.parse(cookie);
				items[id] = undefined;
				$.cookie(name,JSON.stringify(items));
			}
		}
	}
};


var EditorSyntax = {
		EditorHtml: null,
		EditorCss: null,
		EditorJs: null,
		EditorPhp: null,
	Html: function(el,onchange){
		if($('#'+el).length)
		EditorSyntax.EditorHtml = new CodeMirror.fromTextArea(el, {
  			height: $('#'+el).height()+'px',
  			textWrapping: false,
    		parserfile: ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js"],
    		stylesheet: [GLOBAL__PATH_JAVASCRIPT+"codemirror/css/xmlcolors.css", GLOBAL__PATH_JAVASCRIPT+"codemirror/css/jscolors.css", GLOBAL__PATH_JAVASCRIPT+"codemirror/css/csscolors.css"],
    		path: GLOBAL__PATH_JAVASCRIPT+"codemirror/js/",
    		continuousScanning: 500,
   			lineNumbers: true,
   			onChange: onchange
		});
	},
	Css: function(el,onchange){
		if($('#'+el).length)
		EditorSyntax.EditorCss = new CodeMirror.fromTextArea(el, {
  			height: $('#'+el).height()+'px',
  			textWrapping: false,
    		parserfile: ["parsecss.js",],
    		stylesheet: [GLOBAL__PATH_JAVASCRIPT+"codemirror/css/csscolors.css"],
    		path: GLOBAL__PATH_JAVASCRIPT+"codemirror/js/",
    		continuousScanning: 500,
   			lineNumbers: true,
   			onChange: onchange
		});
	},
	Js: function(el,onchange){
		if($('#'+el).length)
		EditorSyntax.EditorJs = new CodeMirror.fromTextArea(el, {
  			height: $('#'+el).height()+'px',
  			textWrapping: false,
    		parserfile: ["tokenizejavascript.js", "parsejavascript.js"],
    		stylesheet: [GLOBAL__PATH_JAVASCRIPT+"codemirror/css/jscolors.css"],
    		path: GLOBAL__PATH_JAVASCRIPT+"codemirror/js/",
    		continuousScanning: 500,
   			lineNumbers: true,
   			onChange: onchange
		});
	},
	Php: function(el,onchange){
		if($('#'+el).length)
		EditorSyntax.EditorPhp = new CodeMirror.fromTextArea(el, {
  			height: $('#'+el).height()+'px',
  			textWrapping: false,
    		parserfile: ["tokenizejavascript.js", "parsejavascript.js"],
    		stylesheet: [GLOBAL__PATH_JAVASCRIPT+"codemirror/css/jscolors.css"],
    		path: GLOBAL__PATH_JAVASCRIPT+"codemirror/js/",
    		continuousScanning: 500,
   			lineNumbers: true,
   			onChange: onchange
		});
	},
	SetAll: function(onchange){
		EditorSyntax.Html('html',onchange);
		EditorSyntax.Php('php',onchange);
		EditorSyntax.Css('css',onchange);
		EditorSyntax.Js('js',onchange);
	},
	Destroy: function(){
		if(EditorSyntax.EditorHtml){EditorSyntax.EditorHtml.toTextArea();EditorSyntax.EditorHtml = null;}
		if(EditorSyntax.EditorCss){EditorSyntax.EditorCss.toTextArea();EditorSyntax.EditorCss = null;}
		if(EditorSyntax.EditorJs){EditorSyntax.EditorJs.toTextArea();EditorSyntax.EditorJs = null;}
		if(EditorSyntax.EditorPhp){EditorSyntax.EditorPhp.toTextArea();EditorSyntax.EditorPhp = null;}
	}
};

var DropDownList = {
	Options: {
		contener: '.drop-down-list',
		title:  '.list-title',
		box: '.list-box',
		start: 0
	},
	Box: null,
	Title: null,
	Init: function(start){
		var self = this;
		start = (start)?start:self.Options.start;
		self.Title = $(self.Options.contener+' '+self.Options.title);
		self.Box = $(self.Options.contener+' '+self.Options.box);
		self.Box.css('display','none');
		self.Title.bind({
			mouseover: function(){$(this).css({'text-decoration':'underline'});},
			mouseout: function(){$(this).css({'text-decoration':'none'});},
			click: function(){
				self.CloseAll();
				self.Click(this);
			}
		});
	},
	Click: function(el){
		var self = this;
		if($(el).next().css('display') == 'none'){
			$(el).addClass('collapse');
			$(el).next().slideDown('slow',function(){self.SetFunctions(this);});
		}else{
			$(el).removeClass('collapse');
			self.RemoveFunction($(el).next());
			$(el).next().slideUp('slow');
		}
	},
	CloseAll: function(){
		Uploader.DestroyCrop();
		Uploader.SetResizer('#img-resize');
		this.Box.slideUp('fast');
		this.Title.removeClass('collapse');
	},
	SetFunctions: function(el){
		if($(el).hasClass('resizer')){Uploader.SetResizer('#img-resize');}
		if($(el).hasClass('cropbox')){Uploader.SetCrop();}
	},
	RemoveFunction: function(el){
		if($(el).hasClass('resizer')){Uploader.DestroyResizer('#img-resize');}
		if($(el).hasClass('cropbox')){Uploader.DestroyCrop();}
	}
};

var Lang = {
	SetLang: function(lang,type,reload){
		if((lang != $.cookie('lang') || reload) && lang){
			Lang.FadeOut();
			Notification.loader('div#topmenu .top','small');
			if(lang){
				$('.lang-box .lang span').removeClass('active');
				$('.lang-box .lang span#a-'+lang).addClass('active');
			}
			if(type == 'list'){
				$.cookie('lang',lang);
				var action = $('form').attr('action');
				var t = $('input[name="t"]').val();
				$('form').attr('action',action.replace('=panel','=ajax'));
				$('input[name="t"]').val('ajax');
				$('form').ajaxSubmit(function(response){
					if(response){$('form .m').html(response);}
					Lang.FadeIn();
					Notification.removeLoader('div#topmenu .top','small');
				});
				$('form').attr('action',action);
				$('input[name="t"]').val('panel');
			}else{
				(GLOBAL_LANGS[lang]['url'])?$('#lang-info').css('background-image','url("'+GLOBAL_LANGS[lang]['url']+'")'):null;
				(GLOBAL_LANGS[lang]['title'])?$('#lang-info b').text(GLOBAL_LANGS[lang]['title']):null;
				this.SaveLangContent($.cookie('lang'));
				this.SetLangContent(lang);
				$.cookie('lang',lang);
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}
		}
	},
	SetLangContent: function(lang){
		$('.lang_'+lang).each(function(){
			var name = $(this).attr('name').replace("["+lang+"]","");
			$('#'+name).val($(this).val());
		});
	},
	//save all language values to a hidden element
	SaveLangContent: function(lang){
		$('.lang_').each(function(){
			var id = $(this).attr('id');
			$('#'+id+'_'+lang).val($(this).val());
		});
	},
	//this function must be called before submit form
	OnSubmit: function(){
		var self = this;
		$('form').submit(function(){self.SetSubmit();});
	},
	SetSubmit: function(){
		this.SaveLangContent($.cookie('lang'));
		$('.lang_').removeAttr('name');
	},
	/*all elements can not be unchecked*/
	CheckLangs: function(){
		$('input[name=langs[]]').click(function(){
			if(!$('input[name=langs[]]:checked').length){
				$('input[name=langs[]]:first').attr('checked',true);
			}
		});
	},
	FadeOut: function(value){
		if(!value) value = 0.3;
		$('.lang-block').fadeTo(0,value);
	},
	FadeIn: function(value){
		if(!value) value = 1;
		$('.lang-block').fadeTo('fast',value);
	},
	ChangeDefaultLang: function(value){
		if(value){
			Notification.loader('div#topmenu .top','small');
			$('.m').fadeTo('fast',0.4);
			$.post(URL_CHANGE_DEFAULT_LANG, "value="+value, function(jsonResponse){
				jsonResponse = JSON.parse(jsonResponse);
				if(jsonResponse.error){Notification.error(jsonResponse.error);}
				if(jsonResponse.message){Notification.success(jsonResponse.message);}
				$('.m').fadeTo('fast',1);
				Notification.removeLoader('div#topmenu .top','small');
			});
		}
	},
	ChangeDefaultLangPanel: function(value){
		if(value){
			Notification.loader('div#topmenu .top','small');
			$('.m').fadeTo('fast',0.4);
			$.post(URL_CHANGE_DEFAULT_LANG_PANEL, "value="+value, function(jsonResponse){
				jsonResponse = JSON.parse(jsonResponse);
				if(jsonResponse.error){Notification.error(jsonResponse.error);}
				if(jsonResponse.message){Notification.success(jsonResponse.message);}
				$('.m').fadeTo('fast',1);
				Notification.removeLoader('div#topmenu .top','small');
			});
		}
	},
	ChangeStatus: function(lang,value){
		if(lang){
			Notification.loader('div#topmenu .top','small');
			$('.m').fadeTo('fast',0.4);
			$.post(URL_CHANGE_STATUS, "lang="+lang+"&value="+value, function(jsonResponse){
				jsonResponse = JSON.parse(jsonResponse);
				if(jsonResponse.error){Notification.error(jsonResponse.error);}
				if(jsonResponse.message){Notification.success(jsonResponse.message);}
				$('.m').fadeTo('fast',1);
				Notification.removeLoader('div#topmenu .top','small');
			});
		}
	},
	MoveLang: function(){
		$(".lang-sortable").sortable({ opacity: 0.6, cursor: 'move',handle: '.move',forceHelperSize: true,  
		update: function(){
			var data = $(this).sortable("serialize"); 
			Notification.loader('div#topmenu .top','small');
			$('.m').fadeTo('fast',0.4);
			$.post(URL_MOVE_LANG, data, function(jsonResponse){
				jsonResponse = JSON.parse(jsonResponse);
				if(jsonResponse.error){Notification.error(jsonResponse.error);}
				if(jsonResponse.message){Notification.success(jsonResponse.message);}
				$('.m').fadeTo('fast',1);
				Notification.removeLoader('div#topmenu .top','small');
			});
		}});
	}
};

var Notification = {
	loader_count : 0,
	loader: function(contener,type){
		if(contener == null){contener = "body";}
		if(!type){
			if($('#body_black').css('display') != 'block'){
				$(contener).css('position','relative');
				$(contener).prepend('<div id="body_black" class="body_black"></div><div id="loader-box"><div id="loader"></div></div>');
				$('#body_black').css({'height':''+$(contener).height()+'px','display':'block'});
				$('#loader-box').css({'left':($(contener).width()/2 - $('#loader-box').width()/2)+'px', 'top':($(contener).height()/3)+'px'});
			}
		}
		if(type == 'no-bg'){
			$(contener).css('position','relative');
			$(contener).append('<div id="loader-box"><div id="loader"></div></div>');
			$('#loader-box').css({'left':($(contener).width()/2 - $('#loader-box').width()/2)+'px', 'top':($(contener).height()/2 - $('#loader').height()/2)+'px'});
		}
		if(type == 'small'){
			$(contener).addClass("loading");
		}
		this.loader_count++;
	},
	removeLoader: function(contener, type){
		if(this.loader_count == 1){
			if(!type){
				$('#body_black').remove();
				$('#loader-box').remove();
			}
			if(type == 'small'){
				$(contener).removeClass("loading");
			}
		}
		if(this.loader_count)this.loader_count--;
	},
	success: function(message,where){
		if(!where) where = '.header:first';
		Notification.removeAll();
		$(where).prepend('<div class="success">'+message+'</div>');
		$.post('clearnotification.html', '', function(theResponse){});
	},
	error: function(message,where){
		if(!where) where = '.header:first';
		Notification.removeAll();
		$(where).prepend('<div class="error">'+message+'</div>');
		$.post('clearnotification.html', '', function(theResponse){});
	},
	alert: function(message){
		alert(message);
	},
	removeAllSlow: function(){
		$('.success').fadeOut("slow",function(){$('.success').remove();});
		$('.error').fadeOut("slow",function(){$('.error').remove();});
		$('.information').fadeOut("slow",function(){$('.information').remove();});
		$('.warning').fadeOut("slow",function(){$('.warning').remove();});
	},
	removeAll: function(){
		$('.success').remove();
		$('.error').remove();
		$('.information').remove();
		$('.warning').remove();
	},
	setError: function(id_element,noFieldError){
		if(id_element){
			if($('#'+id_element).length){
				$('#'+id_element).addClass('error-field');
			}
		}
	},
	setTinyError: function(id_element){
		if($('#'+id_element).hasClass('error-field')){
			Notification.setError(id_element+'_tbl',true);
		}
	}
};

/*important class for sort table in administration panel*/
var Order = {
	Load: function(form,field,type){
		var order = '';
		$('#'+form+' th[id^=_]').css('cursor','pointer');
		$('#'+form).prepend('<input type="hidden" name="_'+field+'" class="order" value="'+type+'" />');
		$('#'+form+' th[id^=_]').bind({
			'mouseover':function(){$(this).addClass('over');},
			'mouseout':	function(){$(this).removeClass('over');},
			'click': function(){
				id = $(this).attr('id').substr(1);
				if(field == id){order = (type == 'asc')?'desc':'asc';}
				else{order = 'asc'}
				$('#'+form+' input.order').remove();
				$('#'+form).prepend('<input type="hidden" name="_'+id+'" value="'+order+'" />');
				$('#'+form).submit();}
		});
		$('#'+form+' th[id^=_]').each(function(){$(this).html('<span>'+$(this).html()+'</span>');});
		$('#'+form+' th[id^=_] span').css('text-decoration','underline');
		Order.Set(form, field,type);
	},
	Set: function(form,field,type){
		$('th#_'+field+' img').remove();
		if(type == 'asc'){$('th#_'+field).append('<img src="public/graf/buttons/bg_asc.gif" alt="order" />');
		}else{$('th#_'+field).append('<img src="public/graf/buttons/bg_desc.gif" alt="order" />');}
	}
};

var Templates = {
	win: null,
	Preview: function(url){
		Templates.win = Page.Window(url,600,730);
	},
	GetHtmlCss: function(){
		if(opener.EditorSyntax){
			var html = opener.EditorSyntax.EditorHtml.getCode();
			var css = opener.EditorSyntax.EditorCss.getCode()
		}else{
			var html = parent.opener.document.getElementById('html').value;
			var css = parent.opener.document.getElementById('css').value;
		}
		$('.content-box').html(html);
		if(css){$('.content-box').prepend('<style>'+css+'</style>');}
	},
	RemoveLast: function(){
		if($('#tpl-elements div.item').length > 1){
			$('#tpl-elements div.item:last').remove();
		}
	},
	AddNext: function(){
		$('<div class="item"><input type="text" class="text" name="elements[name][]" style="width:150px;"/> <input type="text" name="elements[path][]" class="text" style="width:400px;"/></div>').insertAfter('#tpl-elements div.item:last');
	},
	ChangeTpl: function(key,type){
		Notification.loader('div#topmenu .top','small');
		Lang.FadeOut();
		$.post(URL_CHANGE_TPL_TYPE,'key='+key+'&type='+type, function(theResponse){
			theResponse = JSON.parse(theResponse);
			if(theResponse.success == true){
				$('.'+type).attr('checked',false);
				$('.'+type+'_'+key).attr('checked',true);
			}else if(theResponse.error){Notification.error(theResponse.error);}
			Lang.FadeIn();
			Notification.removeLoader('div#topmenu .top','small');
		});
	},
	ChangePermission: function(key,val){
		Notification.loader('div#topmenu .top','small');
		Lang.FadeOut();
		$.post(URL_CHANGE_TPL_PERMISSION,'key='+key+'&val='+val, function(theResponse){
			theResponse = JSON.parse(theResponse);
			if(theResponse.success == true){
			}else if(theResponse.error){Notification.error(theResponse.error);}
			Lang.FadeIn();
			Notification.removeLoader('div#topmenu .top','small');
		});
	}
	
};


/* for browser version */
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	checkBrowser: function (element){
		if(BrowserDetect.browser == 'Explorer' && BrowserDetect.version <= 6){
			if(!element){element = '.header:first';}
			$(element).append(
			'<div class="ie">'+
				'<h2>'+LangJs['_YOUR_BROWSER_IS_NO_LONGER_SUPPORTED']+'.</h2>'+
				'<a target="_blank" href="http://www.google.com/chrome/index.html?brand=CHNY&utm_campaign=en&utm_source=en-et-youtube&utm_medium=et"><img src="./public/graf/ie6/chrome.gif" alt="Chrome" /></a>'+
				'<a target="_blank" href="http://www.mozilla.com/?from=sfx&uid=267821&t=449"><img src="./public/graf/ie6/firefox.gif" alt="Firefox" /></a>'+
				'<a target="_blank" href="http://www.apple.com/safari/"><img src="./public/graf/ie6/safari.gif" alt="Safari" /></a>'+
				'<a target="_blank" href="http://www.opera.com/browser/"><img src="./public/graf/ie6/opera.gif" alt="Opera" /></a>'+
				'<a target="_blank" href="http://www.microsoft.com/windows/internet-explorer/default.aspx"><img src="./public/graf/ie6/ie8.gif" alt="Internet Explorer 8" /></a>'+
			'</div>'
			);
		}
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};


/*SHOP CLASS*/
var SCart = {
	Add: function(id){
		var self = this;
		Notification.loader();
		$.post(URL_CART_ADD,'id='+id+'&ajax=1', function(theResponse){
			if(IsJsonString(theResponse)){
				theResponse = JSON.parse(theResponse);
				self.UpdateCart(theResponse.count, theResponse.amount,theResponse.currency);
			}
			Notification.removeLoader();
		});
	},
	UpdateCart: function(count, amount,currency){
		$('#shop-cart .count').html(count);
		$('#shop-cart .amount').html(amount);
		$('#shop-total-cost').html(amount);
		if(currency) $('#shop-cart .currency').html(currency);
	},
	ShowEmptyCart: function(){
		$('#table-cart tbody').append('<tr><td colspan="5" class="no-results">'+LangJs['_CART_IS_EMPTY']+'</td></tr>');
	},
	Delete: function(id){
		var self = this;
		if(id){
			Notification.loader();
			$.post(URL_CART_DELETE,'id='+id, function(theResponse){
				if(IsJsonString(theResponse)){
					theResponse = JSON.parse(theResponse);
					if(theResponse.success){
						self.UpdateCart(theResponse.count, theResponse.amount);
						$('#table-cart #tr_'+id).fadeOut('fast',function(){$(this).hide();});
						if(theResponse.count == 0 && !theResponse.products){
							self.ShowEmptyCart();
							$('.total-cost').parent().parent().parent().remove();
							$('.delivery-and-payments').remove();
							$('.next-step').remove();
							$('.cart-info').remove();
						}
					}
				}
				Notification.removeLoader();
			});
		}
	},
	ChangeCount: function(id){
		var self = this;
		Notification.loader();
		var count = $('#count_'+id).val();
		$.post(URL_CART_CHANGE_COUNT,'id='+id+'&count='+count, function(theResponse){
				if(IsJsonString(theResponse)){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success){
					self.UpdateCart(theResponse.count, theResponse.amount);
					$('#amount_'+id).html(theResponse.product_count);
				}
			}
			Notification.removeLoader();
		});
	},
	ChangeDelivery: function(id, payments){
		if(payments){
			var arr = payments.split(',');
			$('.payments li input[type = "radio"]').each(function(){
				if(!PHP.in_array($(this).val(),arr)){
					$(this).attr('checked',false);
					$(this).parent().hide();
				}else{$(this).parent().show();}
			});
		}
		$('#delivery-'+id).attr('checked',true);
		$('.delivery-and-payments .remarks').hide();
		if($('.delivery-and-payments #remarks-'+id).css('display') == 'none'){
			$('.delivery-and-payments #remarks-'+id).show();
		}
		this.AddDelivery(id);
	},
	ChangePayments: function(id){
		var self = this;
		$('#payment-'+id).attr('checked',true);
		$.post(URL_CART_CHANGE_PAYMENT,'id='+id, function(theResponse){});
	},
	AddDelivery: function(id){
		var self = this;
		$.post(URL_CART_CHANGE_DELIVERY,'id='+id, function(theResponse){
				if(IsJsonString(theResponse)){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success){
					self.UpdateCart(theResponse.count, theResponse.amount);
				}
			}
		});
	},
	ShowInfo: function(id){
		if(id){
			if($('#info-'+id).css('display') == 'none'){
				$('.info').hide();
				$('#info-'+id).show();
			}else{this.HideInfo(id);}
		}
	},
	HideInfo: function(id){
		if(id){
			$('#info-'+id).hide();
		}
	},
	ShowAdress: function(el){
		if($(el).attr('checked')){$('.shipping-address').slideDown('fast');
		}else{$('.shipping-address').slideUp('fast');}
	},
	ShowInvoice: function(el){
		if($(el).attr('checked')){$('.shop-invoice').slideDown('fast');
		}else{$('.shop-invoice').slideUp('fast');}
	}
};

var COrders = {
	ChangeStatus: function(id,value){
		if(id){
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$.post(URL_ORDERS_CHANGE_STATUS, "id="+id+"&value="+value, function(theResponse){
				theResponse = JSON.parse(theResponse);
				if(theResponse.success == true){
					$('.status-'+id).val(value);
					if(value == 3){$('.tr_'+id).removeClass('tr_green');$('.tr_'+id).addClass('tr_red');}
					if(value == 2){$('.tr_'+id).removeClass('tr_red');$('.tr_'+id).addClass('tr_green');}
					if(value != 2 && value != 3){
						$('.tr_'+id).removeClass('tr_green');
						$('.tr_'+id).removeClass('tr_red');
					}
				}else if(theResponse.error){Notification.error(theResponse.error);}
				Lang.FadeIn();
				Notification.removeLoader('div#topmenu .top','small');
			}); 		
		}
	}
};

var CProducts = {
	Move: function(){
		$(".products-list").sortable({ opacity: 0.6, cursor: 'move',handle: '.move',  update: function() {
				var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_PRODUCTS_MOVE, data, function(theResponse){
					$('body').prepend(theResponse);
					Notification.removeLoader('div#topmenu .top','small');
					Lang.FadeIn();
				}); 															 
			}								  
		});
	}
};


var Faq = {
	Show: function(id){
		if($('.fq-'+id).css('display') == 'none'){
			$('.fq-'+id).slideDown('fast');
		}else{
			$('.fq-'+id).slideUp('fast');
		}
	},
	Hide: function(){
		$('.faq .fq').hide();
	}
};

var DeliveryForm = {
	ChangeStatus: function(id,value){
		if(id){
			var data = "id="+id+"&value="+value;
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			if(value == '1'){ $('.tr_'+id).removeClass('tr_red');
			}else{$('.tr_'+id).addClass('tr_red');}
			$.post(URL_DELIVERY_FORM_CHANGE_STATUS, data, function(theResponse){
				$('body').prepend(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 		
		}
	},
	ChangeDefault: function(id){
		if(id){
			var data = "id="+id;
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$('.delivery-form-default').attr('checked',false);
			$('.default-'+id).attr('checked',true);
			$.post(URL_DELIVERY_FORM_CHANGE_DEFAULT, data, function(theResponse){
				$('body').prepend(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 		
		}
	},
	Move: function(){
		$("#delivery_forms").sortable({ opacity: 0.6, cursor: 'move',handle: '.move',  update: function() {
				var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_DELIVERY_FORM_MOVE, data, function(theResponse){
					$('body').prepend(theResponse);
					Notification.removeLoader('div#topmenu .top','small');
					Lang.FadeIn();
				}); 															 
			}								  
		});
	}
};

var PaymentMethod= {
	ChangeStatus: function(id,value){
		if(id){
			var data = "id="+id+"&value="+value;
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			if(value == '1'){ $('.tr_'+id).removeClass('tr_red');
			}else{$('.tr_'+id).addClass('tr_red');}
			$.post(URL_PAYMENT_CHANGE_STATUS, data, function(theResponse){
				$('body').prepend(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 		
		}
	},
	ChangeDefault: function(id){
		if(id){
			var data = "id="+id;
			Notification.loader('div#topmenu .top','small');
			Lang.FadeOut();
			$('.payment-default').attr('checked',false);
			$('.default-'+id).attr('checked',true);
			$.post(URL_PAYMENT_CHANGE_DEFAULT, data, function(theResponse){
				$('body').prepend(theResponse);
				Notification.removeLoader('div#topmenu .top','small');
				Lang.FadeIn();
			}); 		
		}
	},
	Move: function(){
		$("#payment_method").sortable({ opacity: 0.6, cursor: 'move',handle: '.move',  update: function() {
				var data = $(this).sortable("serialize"); 
				Notification.loader('div#topmenu .top','small');
				Lang.FadeOut();
				$.post(URL_PAYMENT_MOVE, data, function(theResponse){
					$('body').prepend(theResponse);
					Notification.removeLoader('div#topmenu .top','small');
					Lang.FadeIn();
				}); 															 
			}								  
		});
	}
};





