function setCookie(c_name, value, expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)
	+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

/* подгрузка страницы ajax */
function loadPiece(href, update) {
	$j('#indicate').show();
    $j.get(href, {}, function(data) {
    	$j(update).html(data);
        prepareLinks();
    });
}

function doPagination(link) {
	var thisHref = $j(link).attr("href");
	var updateEl = $j(link).parents('.jpaging:first');
	loadPiece(thisHref, updateEl);
	return false;
}

function prepareLinks() {
	$j('.ajax-area a').unbind('click');
	$j('.ajax-area a').click(function() {
		return doPagination(this);
	});
}

function toggleAPhelp() {
	if ($j("#carefree_desc").is(":hidden")) {
		$j("#carefree_desc").slideDown("slow");
	} else {
		$j("#carefree_desc").slideUp("slow");
	}
}


function getArticleStatusesByProject(projectId, records, type) {
	if ($j('tr#project_'+projectId).hasClass('selected')) { return ; }
	$j('tr.project').removeClass('selected');
	$j('tr#project_'+projectId).addClass('selected');
	window.location.hash='#project'+projectId;
	var url='/articles/index';
	if ((typeof(projectId)!='undefined')) {
		url=url+'/project:'+projectId;
	}
	if ((typeof(records)!='undefined')) {
		url=url+'/records:'+records;
	}
	if ((typeof(type)!='undefined')) {
		url=url+'/type:'+type;
	}
	$j('#indicate').show();
	$j.get(url, {}, function(data){
		$j('#art_by_status').html(data);
	});
}

function switchProjects(type) {
	if ($j('.project-switch.'+type).hasClass('pressed')) { return; }
	$j('.project-switch').removeClass('pressed');
	$j('.project-switch.'+type).addClass('pressed');
	$j('#indicate').show();
	var url='/articles/index/type:'+type;
	$j.get(url, {}, function(data){
		$j('#articles_container').html(data);
	});
}

/*
 * переключение между статьями и кампаниями, статусами статей и кампаний
 */
function switchProjectView(type, wantedStatus) {
	if (typeof(offStatus)=='undefined') { offStatus='all'; }
	if (typeof(artStatus)=='undefined') { artStatus='all'; }
	var presentStatus=(type=='offers')?offStatus:artStatus;

	if (typeof(wantedStatus)=='undefined') {
		if (type=='offers') {
			wantedStatus = offStatus;
		} else if (type=='articles') {
			wantedStatus = artStatus;
		}
	}

	if ($j('.project-switch.'+type).hasClass('pressed') && presentStatus == wantedStatus) { return; }

	if (type=='offers') { offStatus=wantedStatus; }
	else { artStatus=wantedStatus; }

	$j('.project-switch').removeClass('pressed');
	$j('.project-switch.'+type).addClass('pressed');
	$j('#indicate').show();
	var url= '/articles/index/'+wantedStatus+'/project:'+projectId+'/cmview:'+type + '?' + new Date().getTime();
	$j.get(url, {}, function(data){
		$j('#off_art_container').html(data);
	});
}


function switchArchive(records) {
	if (switchingArchive) { return false; }
	else { switchingArchive=true; }

	$j('#switchArchive').addClass('disabled-button');

	$j('#indicate').show();
	var url='/articles/index/';
	var type=($j('.project-switch.ap').hasClass('pressed'))?'ap':'manual';
	url=url+'type:'+type+'/records:'+records;

	$j.get(url, {}, function(data){
		$j('#articles_container').html(data);
		switchingArchive=false;
	});
}

function formSubmit(eform, eupdate) {
	$j("#indicate").show();
	$j.post(
		$j(eform).attr('action'),
		$j(eform).serialize(),
		function(data) {
			$j(eupdate).html(data);
		}
	);
}

function prettyFormSubmit(eform, eupdate) {
	var str = "";
	function insertInputValue(el) {
		if(el.attr('type') != "submit" && el.attr('type') != "checkbox" && el.attr('type') != "radio" && el.val()) {
			str += "/" + el.attr('name') + ":" + el.val();
		}
		if (el.attr('type') == "checkbox" && el.attr('checked')) {
			str += "/" + el.attr('name') + ":1";
		}
		if (el.attr('type') == "radio" && el.attr('checked')) {
			str += "/" + el.attr('name') + ":" + el.val();
		}
	}
	$j(eform).find("select").each(function(){ insertInputValue($j(this)); });
	$j(eform).find("input").each(function(){ insertInputValue($j(this)); });
	str += "/";
	$j("#indicate").show();

	$j.get($j(eform).attr('action')+str, function(data) {
		$j(eupdate).html(data);
	});
}

/* ТАБЫ */
function miraTabs() {
	//позиционирование табов
	var isIE6 = navigator.userAgent.toLowerCase().indexOf('msie 6') != -1;
	if (!isIE6) {
		var mrg = 0;
		$j('.mrtabs-link .mrtabs-bt').each(function() {
			/*var currentTab = $j(this);
			if (currentTab.css("position") != 'absolute') {
				$j(this).css('left',mrg);
				mrg = mrg - 5;
			}*/
		});

		mrg = 0;
		$j('.mrtabs-js .mrtabs-bt').each(function() {
			$j(this).css('left',mrg);
			mrg = mrg - 5;
		});
	}

	//переключение табов
	$j('.mrtabs-js .mrtabs-bt').click(function(){
		$j('.mrtabs-js .mrtabs-bt').each(function() {
			$j(this).attr('class','mrtabs-bt');
		})
		$j(this).attr('class','mrtabs-bt mrtabs-bt-active');
		setTab();
	});

	setTab();
	function setTab() {
		$j('.mrtabs-js .mrtabs-bt').each(function() {
			if ($j(this).attr('class') == 'mrtabs-bt mrtabs-bt-active') {
				$j('.'+$j(this).attr('id')).css('display','block');
			} else {
				$j('.'+$j(this).attr('id')).css('display','none');
			}
		});
	}
}


$j().ready(function() {
	prepareLinks();
	$j('#indicate').ajaxStop(function(request, settings){
		$j('#indicate').hide();
	});

	$j('a.tooltip-l').cluetip({local: true, cursor: 'pointer',arrows: false});

	switchingArchive=false;

    miraTabs();

	if ($j('.reference-content').length) {
		$j('.reference-content').dialog({
			autoOpen: false,
			position: ['right', 'top'],
			width: 600,
			height: 250,
			minWidth: 250,
			minHeight: 150
		});
	}

	$j(".inline-hint-link").live("click", function() {
		$j(this).siblings("div.inline-hint:first").slideToggle();
		return false;
	});

	$j(".help-me").live("click", function() {
		var refId = $j(this).attr("class").split(" ")[1];
		$j("#ref_"+refId+".reference-content").dialog("open");
		return false;
	});
	
	if (window.location.hash=="#showhint") {
		$j("div.inline-hint").slideDown();
	}
	
    miraTabs();
});

function mtoggle(id) {
	if($j(id).css("display") == 'none') {
		$j(id).show();
	} else {
		$j(id).hide();
	}
}


//максимальное количество ошибок для одного алерта
var maxDisplayErrorsLine = 5;

function alertResultMessage(resp){
	if (resp.result == 'ok') {
		alert(resp.data.message);
	} else {
		var count = (resp.data.errors.length <= maxDisplayErrorsLine) ? resp.data.errors.length : maxDisplayErrorsLine;
		var msg = resp.data.message + ':\r\n';
		for (var i = 0; i < count; i++) {
			msg += resp.data.errors[i][1] + ' - ' + resp.data.errors[i][2] + '\r\n'; 
		}
		if (resp.data.errors.length > maxDisplayErrorsLine) {
			msg += 'Всего ошибок: ' + resp.data.errors.length;
		}
		alert(msg);
	}
}

function htmlResultMessage(resp) {
	var msg = '';
	if (resp.result == 'error') {
		msg = '<ul>';		
		var count = (resp.data.errors.length <= maxDisplayErrorsLine) ? resp.data.errors.length : maxDisplayErrorsLine;
		for (var i = 0; i < count; i++) {
			msg += '<li>' + resp.data.errors[i][1]+' - '+resp.data.errors[i][2] + '</li>';
		}
		if (resp.data.errors.length > maxDisplayErrorsLine) {
			msg += '</ul>'; 
			msg += 'Всего ошибок: ' + resp.data.errors.length;
		} else {
			msg += '</ul>';
		}
	}
	return msg;
}



