$(document).ready(function() {

	$("*").find("a[href='"+window.location.href+"']").each(function(){
		$(this).addClass("current");
	});


	$(".errors").click(function(){
		$(".errors").hide();
	});
	$(".success").click(function() {
		$(".success").hide();
	});
	$('.formErrorMessage').click(function(){
		$('.formErrorMessage').hide();
	});
	$('.formSuccessMessage').click(function(){
		$('.formSuccessMessage').hide();
	});
	//proccess addcontent.phtml page on checkboxes
	if($('#publish_content').attr('checked')==true){
		$('#datepicker').attr("disabled",true);
		$('#datepicker').css("background","grey");
		$("#publish_on_date").attr("disabled",true);
		$("#publish_on_date").attr("checked",false);
	} else {
		if($('#publish_on_date').attr('checked')==true){
			$('#datepicker').attr("disabled",false);
			$('#datepicker').css("background","#FFE45C");
			$("#publish_on_date").attr("disabled",false);
		} else {
			$('#datepicker').attr("disabled",true);
			$('#datepicker').css("background","grey");
			$("#publish_on_date").attr("disabled",false);
		}
	}
	$('#publish_content').click(function() {
		if($('#publish_content').attr('checked')==true){
			$('#datepicker').attr("disabled",true);
			$('#datepicker').css("background","grey");
			$('#datepicker').val("");
			$("#publish_on_date").attr("checked",false);
			$("#publish_on_date").attr("disabled",true);
		} else {
			$('#datepicker').attr("disabled",true);
			$("#publish_on_date").attr("disabled",false);
		}
	});
	$('#publish_on_date').click(function() {
		if($('#publish_on_date').attr('checked')==true){
			$('#datepicker').attr("disabled",false);
			$('#datepicker').css("background","#FFE45C");
			$('#datepicker').datepicker("setDate", new Date());
		} else {
			$('#datepicker').attr("disabled",true);
			$('#datepicker').css("background","grey");
			$('#datepicker').val("");
		}
	});
	/*
 *END proccess the add new page
 **/    
	$('#editContentForm, #addContentForm').submit(function(){
		content =  encodeURIComponent($('#admincontentarea').val());
		publish_content = $('#publish_content').attr('checked');
		publish_on_date = $('#publish_on_date').attr('checked');
		datepicker = $('#datepicker').val();
		var ctype = $('#ctype').val();
		if(publish_content==true) {
			publish_content = 1;
		} else {
			publish_content = 0;
		}
		if(publish_on_date==true) {
			publish_on_date = 1;
		} else {
			publish_on_date = 0;
		}
		jQuery.ajax({
			type: 'post',
			url: this.action,
			data: "admincontentarea="+content+"&publish_content="+publish_content+"&publish_on_date="+publish_on_date+"&datepicker="+datepicker+'&ctype='+ctype,
			success: function(response) {
				if(response == 'success') {
					top.location.reload();
					top.location.reload();
				}
			}
		});
		return false;
	})
	//404 page management
	$('#edit404').click(function() {
		var wsUrl = $('#hid-main-wsurl').val();
		//checking that 404 page exists
		jQuery.ajax({
			type: 'post',
			url: wsUrl + "sys/backend_page/checknotfound",
			success: function(response) {
				if(response == 'fail') {
					alert('404 Page does not exists. You should create it.');
				} else {
					top.location = response;
				}
			}
		});
	})
	//show/hide frontadmin panel
	$('#showhide').click(function(){
		$('#admincpanel').toggle();
	});
	$('#cantDeletePage').animate({
		opacity: 0
	}, 6000,  function(){
		$('#cantDeletePage').hide()
	});
	//edit and add form submition
	$('#addHeader, #editHeader').submit(function(){
		//content = encodeURIComponent($(':input:textarea').val());
		content = ($('#editheader').val());
		var ctype = $('#ctype').val();
		jQuery.ajax({
			type: "post",
			url: this.action,
			data: "admincontentarea="+escape(content)+"&ctype="+ctype,
			success: function(response) {
				if(response == 'success') {
					top.location.reload();
				}
			}
		});
		return false;
	})
})




function showDiv(param)
{
	switch(param)
	{
		case 'small':
			$("#images_medium").removeClass("show_div");
			$("#images_large").removeClass("show_div");
			$("#images_original").removeClass("show_div");
			$("#list_files").removeClass("show_div");
			$("#content_variables_maker").removeClass("show_div");
			$("#images_small").toggleClass("show_div");
			break;
		case 'medium':
			$("#images_small").removeClass("show_div");
			$("#images_large").removeClass("show_div");
			$("#images_original").removeClass("show_div");
			$("#list_files").removeClass("show_div");
			$("#content_variables_maker").removeClass("show_div");
			$("#images_medium").toggleClass("show_div");
			break;
		case 'large':
			$("#images_medium").removeClass("show_div");
			$("#images_small").removeClass("show_div");
			$("#images_original").removeClass("show_div");
			$("#list_files").removeClass("show_div");
			$("#content_variables_maker").removeClass("show_div");
			$("#images_large").toggleClass("show_div");
			break;
		case 'files':
			$("#images_medium").removeClass("show_div");
			$("#images_small").removeClass("show_div");
			$("#images_large").removeClass("show_div");
			$("#images_original").removeClass("show_div");
			$("#content_variables_maker").removeClass("show_div");
			$("#list_files").toggleClass("show_div");
			break;
		case 'original':
			$("#images_medium").removeClass("show_div");
			$("#images_small").removeClass("show_div");
			$("#images_large").removeClass("show_div");
			$("#list_files").removeClass("show_div");
			$("#content_variables_maker").removeClass("show_div");
			$("#images_original").toggleClass("show_div");
			break;
		case 'variables_maker':
			$("#images_medium").removeClass("show_div");
			$("#images_small").removeClass("show_div");
			$("#images_large").removeClass("show_div");
			$("#images_original").removeClass("show_div");
			$("#list_files").removeClass("show_div");
			$("#content_variables_maker").toggleClass("show_div");
			break;
	}
}

function loadImages(urlwebsite,folder)
{
	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/loadimagesforeditcontent/',
		data: ({
			folder : folder,
			textarea: 'admincontentarea'
		} ),
		dataType: 'json',
		success: function(object){
			$("#images_small").html(object.small);
			$("#images_medium").html(object.medium);
			$("#images_large").html(object.large);
			$("#images_original").html(object.original);
		}
	});
}

function loadImagesForRemoveThings(urlwebsite,folder)
{
	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/loadimagesforremovethings/',
		data: ({
			folder : folder
		}),
		dataType: 'html',
		success: function(data){
			$("#removethings_images").html(data);
		}
	});
}

function insertFeaturedAreasInContent(form)
{
	var regDigit = /^([0-9]{1,10})$/;
	var elm = form.list_featured_areas;
	var name = elm.options[elm.selectedIndex].value;
	var max = form.featured_areas_max.value;
	var max_characters = form.featured_areas_max_characters.value;
	var errors = new Array();
	if(name == '') {
		errors.push(1);elm.style.border ='1px solid red';
	} else {
		elm.style.border ='1px solid #ccc';
	}

	if(!max.match(regDigit) || max <= 0) {
		errors.push(1);form.featured_areas_max.style.border ='1px solid red';
	} else {
		form.featured_areas_max.style.border ='1px solid #ccc';
	}

	if(!max_characters.match(regDigit) || max_characters <= 0) {
		errors.push(1);form.featured_areas_max_characters.style.border ='1px solid red';
	} else {
		form.featured_areas_max_characters.style.border ='1px solid #ccc';
	}

	if(errors.length > 0) {
		return;
	}
	var str = '{$featuredarea'+(form.featured_areas_img.checked == true?'img':'')+':';
	str += name+':';
	str += (max > 0?max+':':'4:');
	str += (max_characters > 0?max_characters:'200');
	str += (form.featured_areas_random.checked == true?':random':'')+'}'
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertExternalRSS(form)
{
	var regDigit = /^([0-9]{1,10})$/;
	var url = form.url.value;
	var maxResult = form.max_result.value;
	var maxCharacters = form.max_characters.value;

	var errors = new Array();
	if(url == '') {
		errors.push(1);form.url.style.border ='1px solid red';
	} else {
		form.url.style.border ='1px solid #ccc';
	}

	if(!maxResult.match(regDigit) || maxResult <= 0) {
		errors.push(1);form.max_result.style.border ='1px solid red';
	} else {
		form.max_result.style.border ='1px solid #ccc';
	}

	if(maxCharacters!=""){
		if(!maxCharacters.match(regDigit) || maxCharacters <= 0) {
			errors.push(1);form.max_characters.style.border ='1px solid red';
		} else {
			form.max_characters.style.border ='1px solid #ccc';
		}
	}
	if(errors.length > 0) {
		return;
	}
	url = url.replace("http://", "");
	url = url.replace("https://", "");
	var str = '{$xrss:';
	str += url+':';
	str += maxResult;
	str += (maxCharacters > 0?':'+maxCharacters+'}':'}');
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertRelatedInContent(form)
{
	var regDigit = /^([0-9]{1,10})$/;
	var keywords = form.related_count_keywords.value;
	var max = form.related_max.value;
	var errors = new Array();
	if(!keywords.match(regDigit) || keywords <= 0) {
		errors.push(1);form.related_count_keywords.style.border ='1px solid red';
	} else {
		form.related_count_keywords.style.border ='1px solid #ccc';
	}
	if(!max.match(regDigit) || max <= 0) {
		errors.push(1);form.related_max.style.border ='1px solid red';
	} else {
		form.related_max.style.border ='1px solid #ccc';
	}
	if(errors.length > 0) {
		return;
	}
	var str = '{$related'+(form.related_img.checked == true?'img':'')+':';
	str += keywords+':';
	str += (max > 0?max:'4')+'}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertSwapper(form)
{    
	var regDigit = /^([0-9]{1,10})$/;
	var folder = form.folder.options[form.folder.selectedIndex].value;
	var time = form.time.value;
	var imgWidth = form.imgWidth.value;
	var imgHeight = form.imgHeight.value;
	var errors = new Array();
	if(!imgWidth.match(regDigit) && imgWidth != '') {
		errors.push(1);form.imgWidth.style.border ='1px solid red';
	}
	if(imgWidth == '' || imgWidth == 0) {
		imgWidth = 100;
	}
	if(folder == '') {
		errors.push(1);form.folder.style.border ='1px solid red';
	} else {
		form.folder.style.border ='1px solid #ccc';
	}
	if(form.slideshow.checked == true && (!time.match(regDigit)  && time!='' || time <= 0) ) {
		errors.push(1);
		form.time.style.border ='1px solid red';
	} else {
		form.time.style.border ='1px solid #ccc';
	}

	if(imgHeight=='' || imgHeight==0){
		imgHeight = imgWidth;
	}

	if(errors.length > 0) {
		return;
	}
	var str = '{$imgrotator:'+folder+':'+(form.slideshow.checked == true?'1:'+time:'0')+':'+ imgWidth +':'+ imgHeight +'}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertPagesList(form)
{
  
	var category = form.categories.options[form.categories.selectedIndex].value;

	var errors = new Array();
	if(category == '') {
		errors.push(1);form.categories.style.border ='1px solid red';
	} else {
		form.categories.style.border ='1px solid #ccc';
	}

	if(errors.length > 0) {
		return;
	}
	var str = '{$pageslist:'+category+':'+(form.pagesWithImage.checked == true?'1':'0')+'}';
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
}

function insertGallery(form, urlwebsite)
{
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;
	var regDigit = /^([0-9]{1,10})$/;
	var new_gallery = form.gallery_name.value;
	new_gallery = new_gallery.replace(ltrim,'');
	new_gallery = new_gallery.replace(rtrim,'');
	var elm = form.list_galleries;
	var t_elm = form.gallery_thumbnails;
	var thumbnails = t_elm.value;
	var name;
	if(new_gallery != ''){
		name = new_gallery;
	}else {
		name = elm.options[elm.selectedIndex].value;
	}
	var errors = new Array();
	if(name == '') {
		errors.push(1);elm.style.border ='1px solid red';
	} else {
		elm.style.border ='1px solid #ccc';
	}
	if(!thumbnails.match(regDigit) || thumbnails <= 0) {
		errors.push(1);t_elm.style.border ='1px solid red';
	} else {
		t_elm.style.border ='1px solid #ccc';
	}
	if(errors.length > 0) {
		return;
	}
    
	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/savesettingsforgallery/',
		data: ({
			gallery : name,
			thumbnails : thumbnails,
			crop : form.gallery_crop.checked,
			lightbox : form.gallery_lightbox.checked,
			caption : form.gallery_caption.checked
		}),
		dataType: 'html',
		success: function(data){
			if(data != '')
			{
				var obj = eval('('+data+')');
				if(obj.save) {
					form.gallery_name.value = '';
				}
				if(obj.new_gallery) {
					name = obj.gallery;elm.options[elm.length] = new Option(name, name, false, true);
				}
				elm.disabled='';
				var str = '{$gallery:'+name+'}';
				$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, str);
			}
		}
	});
}

function insertForm(form, urlwebsite)
{
	var new_form = form.formname.value;
	var elm = form.forms_list;
	var name="";
	if(new_form != ''){
		name = trim(new_form);
	}else {
		name = trim(elm.options[elm.selectedIndex].value);
	}
    
	var errors = new Array();
	if(name == '') {
		errors.push(1);elm.style.border ='1px solid red';
	} else {
		elm.style.border ='1px solid #ccc';
	}
	if(errors.length > 0) {
		return;
	}
	var result="";
	if(form.formcaptcha.checked)
	{
		result = '{$form:'+name+':captcha}';
	}else
	{
		result = '{$form:'+name+'}';
	}
   
	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, result);
}

function insertSearch(form,currentPageId,currentNavName)
{
	var elm = form.pages_list;
	var pageId = trim(elm.options[elm.selectedIndex].value);
	var pageNavName = trim(elm.options[elm.selectedIndex].text);
	
	if(pageId==-1)
	{
		result = "{$search_form:"+currentPageId+"} <br/><br/>  ======== <b>CODE TO INSERT IN '"+currentNavName+"' page ONLY(remove from here)</b>  ========  <br/>{$search_result} OR {$search_result_img} if you want the results to display page images.<br/> ============================================================== ";
	}else
	{
		result = "{$search_form:"+pageId+"} <br/><br/>  ======== <b>CODE TO INSERT IN '"+pageNavName+"' page ONLY(remove from here)</b>  ========  <br/>{$search_result} OR {$search_result_img} if you want the results to display page images.<br/> ============================================================== ";
	}

	$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, result);
}

function loadSettingsForGallery(gallery, form, urlwebsite)
{
	if(gallery == '') {
		form.reset();return;
	}

	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/loadsettingsforgallery/',
		data: ({
			gallery : gallery
		}),
		dataType: 'html',
		success: function(data){
			if(data != '')
			{
				var obj = eval('('+data+')');
				form.gallery_thumbnails.value = obj.thumbnails;
				if(obj.crop=='1'){
					form.gallery_crop.checked=true;
				}else{
					form.gallery_crop.checked=false;
				}
				if(obj.lightbox=='1'){
					form.gallery_lightbox.checked=true;
				}else{
					form.gallery_lightbox.checked=false;
				}
				if(obj.caption=='1'){
					form.gallery_caption.checked=true;
				}else{
					form.gallery_caption.checked=false;
				}
			}
		}
	});
}
function deletePictureInGallery(gallery, image, urlwebsite)
{
	if(gallery == '' || image == '') {
		return;
	}
	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/deletepictureingallery/',
		data: ({
			gallery : gallery,
			image : image
		}),
		dataType: 'html',
		success: function(data){
			if(data != '')
			{
				var obj = eval('('+data+')');
				if(obj.del){
					document.getElementById('gallery_image_'+image).style.display = 'none';
				}
				if(obj.delete_folder){
					document.getElementById('gallery_'+gallery).style.display = 'none';
				}
			}
		}
	});
}
/*start process comments */

function addComment(containerId,commentId,countToShow,requestedPage,publishedByDefault){
    
	$('#comment-captcha-invalid-error-'+commentId).hide();
	var websiteUrl = $('#websiteUrl').val();
	var content = encodeURIComponent($('#post-content-'+commentId).val());
	var sign = encodeURIComponent($('#sign-'+commentId).val());
	var email = encodeURIComponent($('#email-'+commentId).val());
	var website = encodeURIComponent($('#website-'+commentId).val());
	var keyword = encodeURIComponent($('#keyword-'+commentId).val());
	var topic = encodeURIComponent($('#topic-'+commentId).val());
	var publishedbydefault = encodeURIComponent($('#publishedbydefault-'+commentId).val());
	var notify = $('#notify-'+commentId).attr('checked');

	var captchaInput = encodeURIComponent($('#captcha-input').val());
	var captchaId = encodeURIComponent($('#captcha-id').val());

	jQuery.ajax({
		type: "post",
		url: ''+websiteUrl+'sys/backend_ajax/addcomment/',
		data: "content="+content+"&sign="+sign+"&email="+email+"&website="+website+"&containerId="+containerId+"&topic="+topic+"&keyword="+keyword+"&publishedbydefault="+publishedbydefault+"&notify="+notify+"&captcha-input="+captchaInput+"&captcha-id="+captchaId+"&requestedPage="+requestedPage,
		success: function(response) {
			var arr = response.split('~');
         
			if(arr[0]!="captacha error")
			{
				if(publishedByDefault==1){
					$('#comments-ol-'+commentId).prepend(arr[0]);
					var olArray  = $('#comments-ol-'+commentId+' li').get();
					if(olArray){
						for(var i =countToShow;i<olArray.length;i++)
						{
							olArray[i].style.display='none';
						}

						if(olArray.length>countToShow)
						{
							$("#commentslinkholder").empty();
							$("#commentslinkholder").html('<a href="javascript:void(0);" onclick="showHideComments(\''+commentId+'\',\''+countToShow+'\');" id="show-all-comments-'+commentId+'"  title="Show All Comments" >Show all comments</a>');
						}

						$('#captcha-input').val('');
						$('#captcha-id').val(arr[1]);
						$('#captcha-image').attr('src',websiteUrl+'public/tmp/'+arr[1]+'.png');

						$('.success').show();
						$('#added').show();
                
					}
				}else
				{
					$('#captcha-input').val('');
					$('#captcha-id').val(arr[1]);
					$('#captcha-image').attr('src',websiteUrl+'public/tmp/'+arr[1]+'.png');
					$('.success').show();
					$('#addedwait').show();
				}

			}else
			{ //capthca error
				hideCommentErrors(commentId);
				$('#sign-'+commentId).val(arr[1]);
				$('#email-'+commentId).val(arr[2]);
				$('#website-'+commentId).val(arr[3]);

				if(arr[4]==1){
					$('#notify-'+commentId).attr('checked',true);
				}
                  
            
				$('#post-content-'+commentId).val(arr[5]);
				$('#captcha-id').val(arr[6]);
				$('#captcha-image').attr('src',websiteUrl+'public/tmp/'+arr[6]+'.png');
				$('#comment-errors-'+commentId).show();
				$('#comment-captcha-invalid-error-'+commentId).show();
			}
		//top.location.reload();
		}
        
	});
      
	$('#sign-'+commentId).val("");
	$('#email-'+commentId).val("");
	$('#website-'+commentId).val("");
	$('#post-content-'+commentId).val("");
	$('#notify-'+commentId).attr("checked",false);
}

function publishComment(commentId)
{
	var websiteUrl = $('#websiteUrl').val();
	if(commentId>0)
	{
		jQuery.ajax({
			type: "post",
			url: ''+websiteUrl+'sys/backend_ajax/publishcomment/',
			data: "id="+commentId,
			success: function(response) {
				var id;
				if(response.length>20)
				{
					var arr = response.split("<br");
					id = arr[0];
				}else
				{
					id = response;
				}
				
				$('#comment-item-li-'+id).attr('style','border:1px solid #DDDDDD;');
				$('#publish-link-'+id).empty();
			}
		});
	}

}

function hideCommentErrors()
{
	$(".errors").click(function()
	{
		$(".errors").hide();
	});

	$(".success").click(function()
	{
		$(".success").hide();
	});
/*$('#comment-name-empty-error-'+id).hide();
    $('#comment-email-empty-error-'+id).hide();
    $('#comment-content-empty-error-'+id).hide();
    $('#comment-email-regex-error-'+id).hide();
    $('#comment-captcha-empty-error-'+id).hide();    
    $('#comment-errors-'+id).hide();*/
}

function checkPostCommentForm(id)
{
	hideCommentErrors(id);
	var result = true;
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;
    
	document.getElementById('sign-'+id).value = document.getElementById('sign-'+id).value.replace(ltrim,'');
	document.getElementById('sign-'+id).value = document.getElementById('sign-'+id).value.replace(rtrim,'');

	document.getElementById('email-'+id).value = document.getElementById('email-'+id).value.replace(ltrim,'');
	document.getElementById('email-'+id).value = document.getElementById('email-'+id).value.replace(rtrim,'');

	document.getElementById('post-content-'+id).value = document.getElementById('post-content-'+id).value.replace(ltrim,'');
	document.getElementById('post-content-'+id).value = document.getElementById('post-content-'+id).value.replace(rtrim,'');

	document.getElementById('captcha-input').value = document.getElementById('captcha-input').value.replace(ltrim,'');
	document.getElementById('captcha-input').value = document.getElementById('captcha-input').value.replace(rtrim,'');

	if(document.getElementById('sign-'+id).value == '')
	{
        
		$('#comment-errors-'+id).show();
		$('#comment-name-empty-error-'+id).show();
		result = false;
	}

	if(document.getElementById('email-'+id).value == '')
	{
		$('#comment-errors-'+id).show();
		$('#comment-email-empty-error-'+id).show();
		result = false;

	}else
	{
		var email =  $('#email-'+id).val();
		if(!checkEmail(email))
		{
			$('#comment-errors-'+id).show();
			$('#comment-email-regex-error-'+id).show();
			result = false;
		}
	}

	if(document.getElementById('post-content-'+id).value == '')
	{
		$('#comment-errors-'+id).show();
		$('#comment-content-empty-error-'+id).show();
		result = false;
	}

	if(document.getElementById('captcha-input').value == '')
	{
		$('#comment-errors-'+id).show();
		$('#comment-captcha-empty-error-'+id).show();
		result = false;
	}

	return result;
}

function deleteComment(id)
{
	websiteUrl = $('#hid-main-wsurl').val();

	jQuery.ajax({
		type: "post",
		url: ''+websiteUrl+'sys/backend_ajax/deletecomment/',
		data: "id="+id,
		success: function(response) {
			if(response){
				// $('#comment-'+id).remove();
				top.location.reload();
			}
		}
	});
}

function showHideComments(id,countToShow)
{
	var olArray  = $('#comments-ol-'+id+' li').get();
    
	if($('#show-all-comments-'+id).html()=='Show all comments')
	{
		for(i=countToShow;i<olArray.length;i++){
			olArray[i].style.display='block';
		}
		$('#comments-ol-'+id+' li div').css('display','block');
		$('#show-all-comments-'+id).empty().append("Hide Comments");
	}
	else
	{
		if($('#show-all-comments-'+id).html()=="Hide Comments")
		{
			for(i=countToShow;i<olArray.length;i++){
				olArray[i].style.display='none';
			}
			$('#show-all-comments-'+id).empty().append("Show all comments");
		}
	}
}

function checkEmail(email)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) {
		return false;
	}else{
		return true;
	}
}

/*end process comments*/

function insertPaymentButtonInContent(form, urlwebsite)
{
	var reg = /^[a-zA-Z0-9_\s-]{1,225}$/;
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;
	var elm_name = form.payment_name;
	var elm_list = form.list_payment;
	var elm_content = form.payment_content;
	var content = elm_content.value;
	var name;
	var new_name = elm_name.value;
	new_name = new_name.replace(ltrim,'');
	new_name = new_name.replace(rtrim,'');
	content = content.replace(ltrim,'');
	content = content.replace(rtrim,'');
	if(new_name != '') {
		for(var i=0;i<elm_list.length;i++) {
			if(elm_list.options[i].value == new_name) {
				elm_name.style.border ='1px solid red';
				alert('This name is existed');
				return;
			}
		}
		name = new_name;
	} else {
		name = elm_list.options[elm_list.selectedIndex].value;
	}
	elm_name.style.border ='1px solid #ccc';
	var errors = new Array();
	if(name != '' && name.match(reg)) {
		elm_list.style.border ='1px solid #ccc';
	} else {
		errors.push(1);elm_list.style.border ='1px solid red';
	}
	if(content != '') {
		elm_content.style.border ='1px solid #ccc';
	} else {
		errors.push(1);elm_content.style.border ='1px solid red';
	}
	if(errors.length > 0) {
		return;
	}

	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/insertpaymentbuttonincontent/',
		data: ({
			name : name,
			content : content
		}),
		dataType: 'html',
		success: function(data){
			if(data != ''){
				var obj = eval('('+data+')');
				if(!obj.update) {
					elm_list.options[elm_list.length] = new Option(obj.name, obj.name, false, true);
				}
				elm_name.value = '';
				$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, '{$paymentbutton:'+obj.name+'}');
			}
		}
	});
}

function loadContentForPaymentButton(elm , urlwebsite)
{
	var form = elm.form;
	var name = elm.options[elm.selectedIndex].value;
	if(name == '') {
		form.payment_content.value = '';return;
	}

	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/loadpaymentbuttonbyname/',
		data: ({
			name : name
		}),
		dataType: 'html',
		success: function(data){
			if(data != '') {
				var obj = eval('('+data+')');
				form.payment_content.value =  obj.content;
			}
		}
	});
}

function insertCommentInContent(form, urlwebsite)
{
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;
	var regDigit = /^([0-9]{1,10})$/;
	var elm_t = form.comment_topic;
	var elm_k = form.comment_keyword;
	
	var elm_c = form.comment_count;
	var elm_p = form.comment_publish
	var container_name = form.container_name.value;
	/*
    var topic = elm_t.value;
    topic = topic.replace(ltrim,'');
    topic = topic.replace(rtrim,'');
    var keyword = elm_k.value;
    keyword = keyword.replace(ltrim,'');
    keyword = keyword.replace(rtrim,'');
	*/
	var topic = 'default';
	var keyword = 'default';
	
	var count = elm_c.value;
	var publish = elm_p.checked;
	var errors = new Array();
	/*if(topic == '' || !topic.match(/^[a-zA-Z0-9_\s-]{1,225}$/)) {
        errors.push(1);elm_t.style.border = '1px solid red';
    } else {
        elm_t.style.border ='1px solid #ccc';
    }
    if(keyword == ''  || !keyword.match(/^[a-zA-Z0-9_-]{1,225}$/)) {
        errors.push(1);elm_k.style.border = '1px solid red';
    } else {
        elm_k.style.border ='1px solid #ccc';
    }*/
	if(!count.match(regDigit) || count<= 0) {
		errors.push(1);elm_c.style.border = '1px solid red';
	} else {
		elm_c.style.border ='1px solid #ccc';
	}
	if(errors.length > 0) {
		return;
	}

	$.ajax({
		type : 'POST',
		url:''+urlwebsite+'sys/backend_ajax/insertcommentincontent/',
		data: ({
			topic : topic,
			keyword : keyword
		}),
		dataType: 'html',
		success: function(data){
			if(data != ''){
				var obj = eval('('+data+')');
				if(obj.exist > 0) {
					alert('This keyword already exists.');
					return;
				}
				if(obj.exist == 0) {
					$('textarea.tinymce').tinymce().execCommand('mceInsertContent',false, '{$comments:'+container_name+':'+topic+':'+keyword+':'+count+':'+(publish==true?'1':'0')+'}');
				}
			}
		}
	});
}

function deleteUser(url,id, elm)
{
	if(url == '' || id < 0) {
		return;
	}

	$.ajax({
		type : 'POST',
		url:''+url+'sys/backend_ajax/deleteuser/',
		data: ({
			id : id
		}),
		dataType: 'html',
		success: function(data){
			if(data > 0){
				elm.parentNode.parentNode.style.display = 'none';
			}
		}
	});
}

function editUser(url, id)
{
	if(url == '' || id < 0) {
		return;
	}
	var form = document.forms[0];
    
	$.ajax({
		type : 'POST',
		url:''+url+'sys/backend_ajax/loaduser/',
		data: ({
			id : id
		}),
		dataType: 'html',
		success: function(data){
			var obj = eval('('+data+')');
			if(obj.nickname != ''){
				form.nickname.value = obj.nickname;
				form.login.value = obj.login;
				form.password.value = obj.password;
				form.email.value = obj.email;
				for(var i=0;i<form.role.options.length;i++) {
					if(form.role.options[i].value == obj.role) {
						form.role.options[i].selected = true;
						break;
					}
				}
				form.id.value = id;
				form.submit.value = 'Update';
				document.getElementById('back_adduserform').style.display = 'block';
			}
		}
	});
}


//replace silo spans back to the links
function replaceNSP() {
	siteUrl = $('#hid-main-wsurl').val();
	$.get(siteUrl + "tmp/pfs.prs", function(data){
		if(data == 'forprsculpting') {
			return;
		}
		pIdsUrls = data;
		var toReplace = $.find('span');
		$.each(toReplace, function() {
			if($(this).hasClass('nsp')) {
				pages = eval('(' + unescape(pIdsUrls) + ')');
				//alert(pages);
				var url = '';
				for(var i=0; i<=pages.length-1; i++) {
					if(pages[i].id == $(this).attr('id')) {
						url = pages[i].url;
					}
				}
				$(this).replaceWith('<a href="'+siteUrl + url+'.html">' + $(this).html() + '</a>');
			}
		})
		$("ul#main_menu li ul li a").addClass("page");
	})
	


}

function utfDecode(utftext)
{
	
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}

	}

	return string;
}

function sendRecovering()
{
	hideAllPasswordMessages();
	var urlwebsite = $('#hid-main-wsurl').val();
	var email = trimSpaces($('#email').val());
	if(email!="" ){
		if(checkMail(email)){
			$.ajax({
				type : 'POST',
				url:''+urlwebsite+'sys/backend_ajax/sendrecoveringlink/',
				data: ({
					email : email
				}),
				success: function(response){
					switch (response)
					{
						case "success":
							$('#email').val('');
							$('#passwordsuccess').show();
							$('#linksent').show();
							$('.forgotpassword').toggle();
						break;

						case "email does not exist":
							$('#passworderrors').show();
							$('#emailnotexists').show();
						break;
					}
				}
			});
		}else{
			hideAllPasswordMessages();
			$('#passworderrors').show();
			$('#validemail').show();
		}
	}else{
		hideAllPasswordMessages();
		$('#passworderrors').show();
		$('#emptyemail').show();
	}

	
}

function showForgotPasswordScreen(){
	$('.forgotpassword').toggle();
	$('.admineditwhat').html("Forgot your password?");
}

function hideAllPasswordMessages(){
	$('#passworderrors').hide();
	$('#passworderrors ul li').hide();
	
	$('#passwordsuccess').hide();
	$('#passwordsuccess ul li').hide();

}


function trimSpaces(str){
	var ltrim = /^\s+/g;
	var rtrim = /\s+$/g;

	str = str.replace(ltrim,'');
	return str.replace(rtrim,'');
}

function checkMail(value) {
	reg = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/;
	if (!value.match(reg)) {
		return false;
	}else{
		return true;
	}
}

function setHeight(){
		$('#imgHeight').val($('#imgWidth').val());
		$('#imgHeight').select();
	}

function addToCart(id)
{
    if (/^([0-9]{1,10})$/.test(id) && id > 0) {
        var urlwebsite = $('#hid-main-wsurl').val();
        $.ajax({
            type : 'POST',
            url : urlwebsite+'sys/backend_shopping/addtocart/',
            data : ({id:id})/*,
            success: function(data){
                    
            }*/
        });
    }
}

function recountOrder() {
    var urlwebsite = $('#hid-main-wsurl').val();
    var toRemove = [];
    var toRecount = [];
    var frm = $('#hc-form');
    var chkbx = $('#cartview-itemsholder').find('input:checkbox:checked');
    var inpToRec = $('#cartview-itemsholder').find('input:text');
    if(chkbx.length) {
	$.each(chkbx, function() {
	    toRemove.push($(this).attr('id'));
	})
    }
    if(inpToRec.length) {
	$.each(inpToRec, function() {
	    toRecount.push($(this).attr('id')+','+$(this).val());
	})
    }
    $('#startmsg').ajaxStart(function(){
	$(this).show();
    });
    $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_shopping/recount/',
	data : ({toremove:json_encode(toRemove), torecount:json_encode(toRecount)}),
	success: function(){
	    top.location.reload();
	}
    });
}