var close_div = '<div style="float:right;margin-right:0px;font-size:18px;cursor:pointer;padding:5px;" onclick="$(this).parent(\'div\').remove();">'+
'<img src="/templates/'+_template.name+'/images/admin/close_red.png" style="border:0;"/>'+
'</div><div style="clear:both;"></div>';
var backgroundDiv = '<div style="position:fixed;width:100%;height:100%;top:0;left:0;background:#000000;opacity:0.8;filter:alpha(opacity=80);z-index:1300;" id="backgroundDiv"></div>';
var prev_href_elem = '';
var closeOnBodyClick = {};
var closeOnBodyClickNoelem = {};
var caneditFormClicked = false;

//TO SOURCE AKA PHP print_r
//alert( this.toSource() );


(function($){

    //if u want add kontrol $().function();
	$.fn.extend({

		//$('#dialog').createDialog({'method' : 'get/post/html', 'url' : '/ajax.php?model=s&page=s', 'data' : 'some1=1&some2=1', 'title' : 'text', 'complete' : function(){}});
		//if live('click') post twice then use document.ready($(elem).click()) method
		createDialog: function(obj){

			close_div = '';
			$(document.body).append( $('#loaderDiv').ajaxDiv({
				'content' : '<img src="/templates/'+_template.name+'/images/admin/ajax-loader-big.gif" style="float:left;"/> <div style="float:left;margin-left:5px;margin-top:15px;">Loading ...</div>', 
				'style' : 'border:5px solid rgb(98, 98, 98);border-radius:0.55em;-moz-border-radius:0.55em;-webkit-border-radius:0.55em;padding:15px;font-weight:bold;'
			}) );
			$('#loaderDiv').center(window);

			var selector = this.selector;
			var dialogElemSelector = 'class';
			var dialogElemSelectorValue = selector.replace('.', '');
			if( selector.substr(0,1) == '#' ){

				dialogElemSelector = 'id';
				dialogElemSelectorValue = selector.replace('#', '');
			}

			if( $(selector).length > 0 )
				$( selector ).remove();

			$(document.body).append('<div '+dialogElemSelector+'="'+dialogElemSelectorValue+'"></div>');
			$(selector).closeByBodyClick('remove');
			closeOnBodyClick[selector].close = false;

			if( obj.method == 'get' ){

				$.get(obj.url, obj.data.replace('?', '')+'&title='+obj.title, function(data){

					var min_width = $(data).css('min-width') ? parseInt($(data).css('min-width')) : $(data).css('width');
					var width = $( data ).width() > min_width ? $( data ).width() : min_width;
					width = parseInt(width);

					var dialogProperties = {'width' : width+25, 'title' : obj.title, 'display' : 'block', 'open' : function(){

						var new_top = ( $(window).height()-$(".ui-dialog").height() )/2;
						if(new_top <= 0) new_top = 10;
						$( ".ui-dialog" ).css({"position" : "fixed", "top" : new_top+"px"});
					}};
					if(typeof obj.dialogProperties != 'undefined')
						$.extend(dialogProperties, obj.dialogProperties);

					$( selector ).html(data);
					$( selector ).dialog(dialogProperties);
					
					var height = $( selector ).height() > ($(window).height()-100) ? ($(window).height()-100)+'px' : 'auto';
					$( selector ).css({'height' : height, 'overflow-y' : 'hidden', 'overflow-x' : 'hidden'});
					if(height != 'auto')
						$( selector ).css({'overflow-y' : 'scroll', 'overflow-x' : 'hidden'});
					if(obj.complete) obj.complete(data);
					$('#loaderDiv').remove();
					closeOnBodyClick[selector].close = true;
				});
			}
			if( obj.method == 'post' ){

				$.post(obj.url+(obj.url.indexOf('?') > -1 ? '&title='+obj.title : '?title='+obj.title), obj.data.replace('?', ''), function(data){

					var min_width = $(data).css('min-width') ? parseInt($(data).css('min-width')) : $(data).css('width');
					var width = $( data ).width() > min_width ? $( data ).width() : min_width;
					width = parseInt(width);

					var dialogProperties = {'width' : width+25, 'title' : obj.title, 'display' : 'block', 'open' : function(){

						var new_top = ( $(window).height()-$(".ui-dialog").height() )/2;
						if(new_top <= 0) new_top = 10;
						$( ".ui-dialog" ).css({"position" : "fixed", "top" : new_top+"px"});
					}};
					if(typeof obj.dialogProperties != 'undefined')
						$.extend(dialogProperties, obj.dialogProperties);

					$( selector ).html(data);
					$( selector ).dialog(dialogProperties);

					var height = $( selector ).height() > ($(window).height()-100) ? ($(window).height()-100)+'px' : 'auto';
					$( selector ).css({'height' : height, 'overflow-y' : 'hidden', 'overflow-x' : 'hidden'});
					if(height != 'auto')
						$( selector ).css({'overflow-y' : 'scroll', 'overflow-x' : 'hidden'});
					if(obj.complete) obj.complete(data);
					$('#loaderDiv').remove();
					closeOnBodyClick[selector].close = true;
				});
			}
			if( obj.method == 'html' ){

				var data = obj.html;
				var min_width = $(data).css('min-width') ? parseInt($(data).css('min-width')) : $(data).css('width');
				var width = $( data ).width() > min_width ? $( data ).width() : min_width;
				width = parseInt(width);

				var dialogProperties = {'width' : width+25, 'title' : obj.title, 'display' : 'block', 'open' : function(){

					var new_top = ( $(window).height()-$(".ui-dialog").height() )/2;
					if(new_top <= 0) new_top = 10;
					$( ".ui-dialog" ).css({"position" : "fixed", "top" : new_top+"px"});
				}};
				if(typeof obj.dialogProperties != 'undefined')
					$.extend(dialogProperties, obj.dialogProperties);

				$( selector ).html(data);
				$( selector ).dialog(dialogProperties);
				
				var height = $( selector ).height() > ($(window).height()-100) ? ($(window).height()-100)+'px' : 'auto';
				$( selector ).css({'height' : height, 'overflow-y' : 'hidden', 'overflow-x' : 'hidden'});
				if(height != 'auto')
					$( selector ).css({'overflow-y' : 'scroll', 'overflow-x' : 'hidden'});
				if(obj.complete) obj.complete(data);
				$('#loaderDiv').remove();
				closeOnBodyClick[selector].close = true;
			}
		},

		dialogDone: function(message){

			var close_div = '<div style="text-align:right;margin-top:-13px;margin-right:-13px;"><img src="/templates/'+_template.name+'/images/admin/close_red.png" class="close_dialog_done pointer"/></div>';

			$(this.selector).after(
				'<div id="dialog_done" style="left:0px;width:100%;position:fixed;z-index:1500;">'+
				'<div style="color:black;font-size:12px;font-weight:bold;width:200px;margin-left:48%;padding:10px;text-align:center;border:1px solid #004000;background:#f0fff0;">'+close_div+$.language(message)+'</div>'+
				'</div>'
			);
			var top = ($('body').height()/2)-($('#dialog_done').height()/2);
			$('#dialog_done').css({'top' : top+'px'});
			$('.close_dialog_done').live('click', function(){

				$('#dialog_done').animate({'opacity' : '0'}, 1000, function(){ $(this).remove(); });
			});
		},

		//var obj = {content : '', style : '', bgDiv : true/false};
		ajaxDiv: function(obj){

			if(typeof obj == 'string') obj = {'content' : obj};

			var selector = this.selector;
			if(!selector) selector = '#ajaxDiv';

			if( $(selector).length > 0 ) $(selector).remove();

			var ajaxDivElem = selector;

			var elem_type = 'id';
			if( selector.substr(0,1) == '.' ){

				elem_type = 'class';
				selector = selector.substr(1);
			}
			if( selector.substr(0,1) == '#' ){

				elem_type = 'id';
				selector = selector.substr(1);
			}

			return '<div '+elem_type+'="'+selector+'" style="background:white;border:1px solid #626262;padding:3px;position:absolute;display:block;z-index:1500;'+obj.style+'">'+
				close_div+
				obj.content+
				'<script type="text/javascript">$(\''+ajaxDivElem+'\').closeByBodyClick(\'remove\');</script>'+
			'</div>';
		},

		//var obj = {content : '', style : '', bgDiv : true/false};
		fadeOutDiv: function(obj){

			if(typeof obj == 'string') obj = {'content' : obj};
			if(typeof obj.style == 'undefined') obj.style = '';

			if( $('#ajaxfadeOutDiv').length > 0 ) $('#ajaxfadeOutDiv').remove();

			$(this.selector).append( 
				'<div style="display:none;background:white;border:1px solid rgb(98, 98, 98);border-radius:0.25em;-moz-border-radius:0.25em;-webkit-border-radius:0.25em;padding:15px;position:absolute;z-index:1500;'+obj.style+'" id="ajaxfadeOutDiv">'+obj.content+'</div>' 
			);
			$('#ajaxfadeOutDiv').center(this.selector);
			$('#ajaxfadeOutDiv').show();
			setTimeout(function(){
				
				$('#ajaxfadeOutDiv').fadeOut(1000, function(){

					$('#ajaxfadeOutDiv').remove();
				});
			}, 1000);
		},

		center: function(element_with){

			var padding_left = $(this.selector).css('padding-left');
			var padding_top = $(this.selector).css('padding-top');

			var margin_left = ( $(element_with).width()-$(this.selector).width()-parseInt(padding_left) )/2;
			var margin_top = ( $(element_with).height()-$(this.selector).height()-parseInt(padding_top) )/2;
			if($(window).scrollTop() > 0){

				var scrollTop = $(window).scrollTop();
				margin_top += scrollTop;
			}
			$(this.selector).css({'left' : margin_left+'px', 'top' : margin_top+'px'});
		},

		//example 1 $('.header-box').closeByBodyClick('hide');
		//example 2 $('.header-btn').closeByBodyClick({'selector' : '.header-box', 'action' : 'hide'});
		closeByBodyClick: function(obj){

			var action = typeof obj == 'string' ? obj : obj.action;
			var deleteElem = typeof obj == 'string' ? false : obj.deleteElem;
			var selector = typeof obj == 'string' ? this.selector : obj.selector;

			if( $(this.selector).length > 0 ){

				if(typeof closeOnBodyClickNoelem[selector] == 'object') deleteElem = true;

				closeOnBodyClick[selector] = {'close' : true, 'action' : action, 'deleteElem' : deleteElem};
				if(typeof obj == 'string'){

					$(this.selector).live('click', function(){

						closeOnBodyClick[selector].close = false;
					});
					$(this.selector).live('mouseleave', function(){

						closeOnBodyClick[selector].close = true;
					});
					$(this.selector).live('mouseenter', function(){

						closeOnBodyClick[selector].close = false;
					});
				}
				else{

					$(this.selector).live('click', function(){

						closeOnBodyClick[selector].close = false;
					});
					$(selector).live('click', function(){

						closeOnBodyClick[selector].close = false;
					});
					$(selector).live('mouseleave', function(){

						closeOnBodyClick[selector].close = true;
					});
					$(selector).live('mouseenter', function(){

						closeOnBodyClick[selector].close = false;
					});
				}
			}
			else{

				closeOnBodyClickNoelem[selector] = {'close' : true, 'action' : action, 'selector' : selector, 'deleteElem' : true};
			}
		},

		reload: function(url){

			var selector = this.selector;

			$.get(url, function(data){

				if( $('#ajaxDiv').length > 0 )
					selector = '#ajaxDiv';

				$(selector).html(close_div+''+data);
			});
		},

		slideBox: function(speed, onComplete){

			if( $(this.selector).css('display') == 'none' ){

				$(this.selector).show(speed, onComplete);
			}
			else{

				$(this.selector).hide(speed, onComplete);
			}
		},

		pjSort: function(){

			$(this).prepend(
				'<a href="'+$.linkJSAppend('?sort='+$(this).attr('id')+'&order=asc')+'" class="sort_res"><img src="/templates/'+_template.name+'/images/admin/sort_asc.png" style="border:0px;"/></a>'+
				'<a href="'+$.linkJSAppend('?sort='+$(this).attr('id')+'&order=desc')+'" class="sort_res"><img src="/templates/'+_template.name+'/images/admin/sort_desc.png" style="border:0px;margin-right:10px;"/></a>'
			);
		},

		scrollTo: function(addTop){

			if( $(this.selector).length > 0 ){

				var scrollTo = $(this.selector).offset().top;
				if(addTop){

					if(addTop < 0)
						scrollTo -= addTop*-1;
					if(addTop > 0)
						scrollTo += addTop;
				}
				$('html,body').animate({scrollTop: scrollTo}, 1000);
			}
		},
		validate: function(json_data){

			var selector = this.selector;

			if($.canJSON(json_data)){

				$.each($.parseJSON(json_data), function(k, v){

					var elemname = k;
					var $elem = $('[name='+k+']', selector);
					var elemtype = $elem[0].nodeName.toLowerCase();
					var prevcolor = $elem.css('color');
					var prevvalue = $elem.val();
					var action = 'addvalue';
					var non_value_elems = 'submit,checkbox,radio,image,file,button';
					if(elemtype == 'input' && non_value_elems.indexOf($elem.attr('type').toLowerCase()) > -1){

						action = 'appendtext';
					}
					if(elemtype == 'select'){

						action = 'appendtext';
					}

					if(action == 'addvalue'){

						$elem.val(v);
						$elem.css({'color' : 'red'});
						$elem.bind('click', function(){

							$elem.val(prevvalue);
							$(this).css({'color' : prevcolor});
						});
					}
					if(action == 'appendtext'){

						$elem.before('<span class="validate-error-label-'+elemname+'" style="color:red;display:block;margin-bottom:3px;">'+v+'</span>');
						$elem.bind('click', function(){

							$('.validate-error-label-'+elemname).remove();
						});
					}
				});
			}
		},
		//$('.category').dragAndDrop({'url' : '?model=eshop&page=categorys', 'advanced' : true}, function(){formClicked = true;});
		//advanced - if parent-row is moveable
		//<tr class="nodrag"> - To make non-draggable rows
		//<tr class="nodrop"> - don't allow dropping
		dragAndDrop: function(obj, onReady){

			var elem = this;
			var parentData = '';
			if(obj.advanced == true){

				$('.dragAndDropMouseOver').live('mouseenter', function(){

					parentData = $(this).attr('id');
					if(parentData.indexOf(':row-parent-') > -1){

						var multiId = parentData.split(':');
						parentData = multiId[0].indexOf('row-parent-') > -1 ? multiId[0] : multiId[1];
					}
					if(parentData.indexOf('row-') > -1 && parentData.indexOf('row-parent-') == -1)
						parentData = parentData.replace('row-', 'row-parent-');
				});
				$('.dragAndDropMouseOver').live('mouseleave', function(){

					parentData = '';
				});
			}

			$(elem).tableDnD({
		
				onDragClass: 'contentDrag',
				onDragStart: function(table, row){

					$(row).css({'border' : '2px solid grey'});
					$('tr', elem).addClass('dragAndDropMouseOver');
					$(row).removeClass('dragAndDropMouseOver');
				},
				onDrop: function(table, row) {

					$('tr', elem).removeClass('dragAndDropMouseOver');

					if($(row).attr('id') == undefined || $(row).attr('id').indexOf('row-') == -1){

						alert('Add id="row-$row[\'id\']" into TR element AND id="row-parent-$row[\'id\']" into HEADER TR element IF parent is moveable then id="row-$row[\'id\']:row-parent-$row[\'id\']"');
					}
					else{

						$(row).css({'border' : 'none'});

						var prevData = $(row).prevAll('tr:not(.hidden)').attr('id');
						if(prevData == undefined){

							$(row).prevAll('tr').each(function(k, v){

								if( $(v).attr('id') != undefined && $(v).attr('id').indexOf(':row-parent-') > -1 ){

									var multiId = $(v).attr('id').split(':');
									if(prevData == undefined || prevData.indexOf('row-parent') > -1)
										prevData = multiId[0].indexOf('row-parent-') > -1 ? multiId[1] : multiId[0];
									return false;
								}
							});
						}
						if(prevData == undefined || prevData.indexOf('row-parent') > -1) prevData = 'row-0';

						var currentData = $(row).attr('id');

						var nextData = $(row).nextAll('tr:not(.hidden)').attr('id');
						if(nextData == undefined || nextData.indexOf('row-parent') > -1) nextData = 'row-0';

						if(parentData == undefined) parentData = 'row-parent-0';

						//alert('prevData='+prevData+' currentData='+currentData+' nextData='+nextData+' parentData='+parentData);
						//alert('ajax.php'+obj.url+'&action=dragAndDrop&prevData='+prevData.replace('row-', '')+'&currentData='+currentData.replace('row-', '')+'&nextData='+nextData.replace('row-', '')+'&parentData='+parentData.replace('row-parent-', ''));

						$.get('ajax.php'+obj.url+'&prevData='+prevData.replace('row-', '')+'&currentData='+currentData.replace('row-', '')+'&nextData='+nextData.replace('row-', '')+'&parentData='+parentData.replace('row-parent-', ''), function(data){

							//alert(data);
							if(onReady)
								onReady(data);
						});
					}
				}
			});
		},
        loadScript: function(url, callback) {
            // Adding the script tag to the head as is good manners
            var head = document.getElementsByTagName('head')[0];
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = url;

            // Then bind the event to the callback function.
            // There are several events for cross browser compatibility.
            script.onreadystatechange = callback;
            script.onload = callback;

            // Fire the loading
            head.appendChild(script);
        }
	});

	$.extend({
		
		confirm: function(text){

			confirm_return = false;
			var answer = confirm((text ? text : $.language('delete')));
			confirm_return = answer;
			if (answer){
				return true;
			}
			else{
				return false;
			}
		},

		password: function (length, special) {
			var iteration = 0;
			var password = "";
			var randomNumber;
			if(special == undefined){
				var special = false;
			}
			while(iteration < length){
				randomNumber = (Math.floor((Math.random() * 100)) % 94) + 33;
				if(!special){
					if ((randomNumber >=33) && (randomNumber <=47)) { continue; }
					if ((randomNumber >=58) && (randomNumber <=64)) { continue; }
					if ((randomNumber >=91) && (randomNumber <=96)) { continue; }
					if ((randomNumber >=123) && (randomNumber <=126)) { continue; }
				}
				iteration++;
				password += String.fromCharCode(randomNumber);
			}
			return password;
		},

		ucFirst: function(string) {

			return string.substring(0, 1).toUpperCase() + string.substring(1);
		},

		//$.language('text {first_name} {last_name}', {'first_name' : '$_SESSION['UserData']['first_name']', 'last_name' : 'last name'});
		language: function(language_key, replacement){

			var return_value = '';
			if( typeof language != 'undefined' && language[language_key] ){

				return_value = language[language_key];
			}
			else{

				var model = $.url(window.location.href, 'model');
				var page = $.url(window.location.href, 'page');

				$.ajax({
					type: 'GET',
					url: '/scripts/language.php',
					data: {'language_key' : language_key, 'replacement' : replacement, 'model' : model, 'page' : page},
					async: false,
					cache: true,
					success: function(content){

						return_value = content;
					}
				});
			}
			return return_value;
		},
		//$.link('?model=see&page=kus&page_name=page_name', new Array('page_name'));
		link: function(url, hide_id){

			url = url+(_window.location.loc ? '&'+_window.location.loc+'='+_window.location.loc : '');
			if(!hide_id) hide_id = '';
			hide_id += _window.location.loc;

			var return_value = '';
			var link_key = CryptoJS.MD5(url);
			if( typeof link != 'undefined' && link[link_key] ){

				return_value = link[link_key];
			}
			else{

				$.ajax({
					type: 'GET',
					url: '/scripts/link.php',
					data: {'url' : url, 'hide_id' : hide_id},
					async: false,
					cache: true,
					success: function(content){

						return_value = content;
					}
				});
			}
			return return_value;
		},
		linkAppend: function(url, hide_id){

			url = _window.location.canonical+'&'+url+'&urltype=append'+(_window.location.loc ? '&'+_window.location.loc+'='+_window.location.loc : '');
			if(!hide_id) hide_id = '';
			hide_id += 'urltype,'+_window.location.loc;

			var return_value = '';
			var link_key = CryptoJS.MD5(url);
			if( typeof link != 'undefined' && link[link_key] ){

				return_value = link[link_key];
			}
			else{

				$.ajax({
					type: 'GET',
					url: '/scripts/link.php',
					data: {'url' : url, 'hide_id' : hide_id},
					async: false,
					cache: true,
					success: function(content){

						return_value = content;
					}
				});
			}
			return return_value;
		},

		//key=name&key=value
		linkJS: function(url){

			return _window.location.basic+'&'+url;
		},

		//?sort=this&order=asc
		linkJSAppend: function(url){

			var return_value = window.location.href;
			var return_split = return_value.split('/');
			return_split = return_split[return_split.length-1].split('&');
			var namesInList = [];
			for( var i = 0; i < return_split.length; i++ ){

				var name = return_split[i].split('=')[0].replace('?', '');
				namesInList[i] = name;
			}
			var split_values = url.split('&');
			for( var i = 0; i < split_values.length; i++ ){

				if(split_values[i]){

					var name = split_values[i].split('=')[0].replace('?', '');
					var value = split_values[i].split('=')[1];

					if(value){

						if(namesInList.indexOf(name) > -1){

							return_value = return_value.replace(name+'='+$.url(window.location.href, name), name+'='+value);
						}
						else{

							return_value += '&'+name+'='+value;
						}
					}
					else{

						return_value = return_value.replace('&'+name+'='+$.url(window.location.href, name), '');
					}
				}
			}
			return return_value;
		},

		url: function(url, returnName){

			if( url.indexOf('?') > -1 ){

				url = url.replace(/&amp;/gi, '&');
				var ret = url.split('?')[1].split('&');
				for(var i = 0; i < ret.length; i++){

					var name = ret[i].split('=')[0];
					var value = ret[i].split('=')[1];
					if(name == returnName) return value;
				}
			}
			return '';
		},
		replace_ment: function(key){

			key = key.replace('{', '');
			key = key.replace('}', '');
			if(typeof pregArray[key] == 'string' || typeof pregArray[key] == 'number')
				return pregArray[key];
			return '';
		},

		preg_replace: function(str, dataArray){

			if( typeof str == 'string' ){

				pregArray = dataArray;
				//alert('str'+str);
				str = str.replace(/%7B/g, '{').replace(/%7D/g, '}');
				var return_string = str.replace(/\{([a-zA-Z0-9\__]+)\}/gi, this.replace_ment);
				//alert('return_string '+return_string);
				return return_string;
			}
		},

		preg_match_all: function(regex, haystack){

		   var globalRegex = new RegExp(regex, 'gi');
		   var globalMatch = haystack.match(globalRegex);
		   matchArray = new Array();
		   for (var i in globalMatch) {

			  nonGlobalRegex = new RegExp(regex);
			  nonGlobalMatch = globalMatch[i].match(nonGlobalRegex);
			  matchArray.push(nonGlobalMatch[1]);
		   }
		   return matchArray;
		},

		setCookie: function(c_name,value,exdays){

			var exdate=new Date();
			exdate.setDate(exdate.getDate() + exdays);
			var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
			document.cookie=c_name + "=" + c_value;
		},

		getCookie: function(c_name){

			var i,x,y,ARRcookies=document.cookie.split(";");
			for (i=0;i<ARRcookies.length;i++){

				x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
				y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
				x=x.replace(/^\s+|\s+$/g,"");
				if (x==c_name){

					return unescape(y);
				}
			}
		},
		canJSON: function(value) {

			if(value.length == 0) return false;

			value = value.replace(/^\s+|\s+$/g,"");
			if( value.substr(0,1) == '{' || value.substr(0,1) == '[' ){

				return true;
			}
			return false;
		}
	});
})(jQuery);

$(document).ready(function(){

	$(document).bind('click',function(e) {

		$.each(closeOnBodyClick, function(elem, obj){

			if(obj.close == true){

				if(obj.action == 'remove'){

					$(elem).remove();
				}
				if(obj.action == 'hide'){

					$(elem).hide();
				}
				if(obj.deleteElem == true){

					delete closeOnBodyClick[elem];
				}
			}
		});
		$.each(closeOnBodyClickNoelem, function(elem, obj){

			$(elem).closeByBodyClick(obj);
		});
	});
	$('.delete, .delete_link').live('click', function(){

		return $.confirm($(this).attr('alt'));
	});

	$('.confirm').live('click', function(){

		return $.confirm($(this).attr('alt'));
	});

	$('._blank').live('click', function(){

		window.open(this, $(this).attr('alt') ? $(this).attr('alt') : 'blank');
		return false;
	});

	$('.view_positions').live('click', function(){

		var elem = $(this).attr('href').split('name=');
		elem = elem[1];

		var top = ($(window).height()-($(window).height()-100))/2;
		var left = ($(window).width()-($(window).width()-100))/2;

		$(document.body).append(

			$().ajaxDiv({
				'content' : '<iframe src="/?show_position=1" style="width:'+($(window).width()-100)+'px;height:'+($(window).height()-150)+'px;" frameborder="0" id="position_frame"></iframe>', 
				'style' : 'top:'+top+'px;left:'+left+'px;width:'+($(window).width()-100)+'px;height:'+($(window).height()-100)+'px;'
			})
		);
		$('#position_frame').load(function(){

			var frame_content = $(this).contents().find('body');
			
			frame_content.find('.template_position').click(function(){

				var set_class = $(this).find('font').attr('class');
				$('select[name="'+elem+'"] option[value="'+set_class+'"]').attr({'selected' :'selected'});
				$('#ajaxDiv').remove();
			});
		});
		return false;
	});
	$('.select_all, .select-all').live('click', function(){

		$(this).select();
	});
	$('.pj-sort').each(function(){

		$(this).pjSort();
	});

	$('.can_edit').live('click', function(){

		if(caneditFormClicked == false && $('div', this).css('display') == 'none'){

			$('div', this).show();
			$('span', this).hide();
			$('div > input', this).focus();
			$('div > select', this).focus();
			$('div > textarea', this).focus();
		}

		caneditFormClicked = false;
	});
	$('.can_edit input, .can_edit select, .can_edit textarea').live('click', function(){

		caneditFormClicked = true;
	});
	$('.can_edit_close').live('click', function(){

		var parentElem = $(this).parent('p').parent('div');

		if( parentElem.find('input[type="text"]').length > 0 )
			parentElem.find('input[type="text"]').val( parentElem.find('input[type="hidden"]').val() );
		if( parentElem.find('textarea').length > 0 )
			parentElem.find('textarea').val( parentElem.find('input[type="hidden"]').val() );
		if( parentElem.find('input[type="radio"]').length > 0 ){

			parentElem.find('input[type="radio"]').each(function(){

				this.checked = false;
				if( this.value == parentElem.find('input[type="hidden"]').val() )
					this.checked = true;
			});
		}
		if( parentElem.find('input[type="checkbox"]').length > 0 ){

			var elem = parentElem.find('input[type="checkbox"]');
			var string = parentElem.find('input[type="hidden"]').val();
			var regex = /\[([^[]*?)\]/g;
			var results = string.match(regex);
			$(results).each(function(){

				var data = this.replace('[', '').replace(']', '');
				$('input[value="'+data+'"]', elem).attr({'checked': 'checked'});
			});
		}
		if( parentElem.find('select').length > 0 ){

			var elem = parentElem.find('select');
			var string = parentElem.find('input[type="hidden"]').val();
			var regex = /\[([^[]*?)\]/g;
			var results = string.match(regex);
			$(results).each(function(){

				var data = this.replace('[', '').replace(']', '');
				$('option[value="'+data+'"]', elem).attr({'selected': 'selected'});
			});
		}

		$('div', parentElem.parent('.can_edit')).hide();
		$('span', parentElem.parent('.can_edit')).show();

		caneditFormClicked = true;
	});

	$('.slideDown').click(function(){

		var css = $(this).attr('class').replace('slideDown', '.slideDownBox').replace(' ', '.');
		$(css).toggle(500);
		return false;
	});
	$('.slideDownCancel').click(function(){

		var css = $(this).parents('.slideDownBox').attr('class').replace(' ', '.');
		$('.'+css).toggle(500);
		return false;
	});

	$('[name=search-data]').click(function(){

		var inputData = '';

		$(this).parents('form').find('input').each(function(k, elem){

			if( elem.type == 'text' || elem.type == 'hidden' ){

				inputData += (inputData ? '&' : '')+elem.name+'='+elem.value;
			}
			else if( elem.type == 'checkbox' && elem.checked == true ){

				inputData += (inputData ? '&' : '')+elem.name+'='+elem.value;
			}
			else if( elem.type == 'radio' && elem.checked == true ){

				inputData += (inputData ? '&' : '')+elem.name+'='+elem.value;
			}
		});
		$(this).parents('form').find('select').each(function(k, elem){

			if( elem.multiple == true ){

				$('option', elem).each(function(k, option){

					if( option.selected == true ){

						inputData += (inputData ? '&' : '')+elem.name+'='+option.value;
					}
				});
			}
			else{

				inputData += (inputData ? '&' : '')+elem.name+'='+elem.value;
			}
		});
		$(this).parents('form').find('textarea').each(function(k, elem){

			inputData += (inputData ? '&' : '')+elem.name+'='+elem.value;
		});

		if( $(this).parents('form').attr('action').indexOf('?') > -1 )
			window.location.href = $(this).parents('form').attr('action')+'&'+inputData;
		else
			window.location.href = $(this).parents('form').attr('action')+'?'+inputData;
		return false;
	});

	$('.history').click(function(){

		window.history.back();
		return false;
	});
});