var beforeSubmitImage = '<img class="beforeSubmitImage" id="beforeSubmitImage" height="16" border="0" width="16" alt="" src="/images/loading.gif"/>';
var formID = '';
function beforeSubmitForm(formData, jqForm, options){
	formID = jqForm[0].id;
	$('#'+formID+' #save').parent().append(beforeSubmitImage);
	$('#'+formID+' #save').hide();
	$('#'+formID+' .error').remove();
}
function responseSubmitForm(data, statusText){
	//alert(data);
	if(data.errors) {
		showErrorSubmit(data.errors);
		$('#'+formID+' #save').show();
		$('.beforeSubmitImage').remove();
	}else if(data.location) {
		window.location = data.location;
	}else {
		$('#messages').html('<div class="message">'+data.message+'</div>');
		$('#'+formID+' #save').show();
		$('.beforeSubmitImage').remove();
	}
	formID = '';
}
function showErrorSubmit(errors){
	for (var i in errors) {
		for (var k in errors[i]){
			if($('#'+i).length){
				$('#'+i).parent().append('<div class="error">'+errors[i][k]+'</div>');
			}else if($("input[name='"+ i +"']").length) {
				$("input[name='"+ i +"']:first-child").parent().parent().append('<div class="error">'+errors[i][k]+'</div>');
			}else if($('#'+i+'-1').length) {
				$('#'+i+'-1').parent().parent().append('<div class="error">'+errors[i][k]+'</div>');
			}			
		}
		
	}
}
function deleteImage(action, sID, item_id){
	if(confirm('Вы желаете удалить?')) {
		$('#'+sID).parent().append(beforeSubmitImage);
		$('#'+sID).hide();
		$.post('/users/'+action+'/deleteimage',{id: item_id}, function(data){
	        if(data == '1'){
	        	$('#'+sID).parent().remove();
	        }else{
	        	$('.beforeSubmitImage').remove();
	        	$('#'+sID).show();
	        }
	    });
	}
    return false;
}
function deleteBulletinImage(iNum){
	if(confirm('Вы желаете удалить?')) {
		$('#deleteImage'+iNum).parent().append(beforeSubmitImage);
		$('#deleteImage'+iNum).hide();
		$.post('/bulletinboard/deletebulletinimage', {num: iNum}, function(data){
	        if(data == '1'){
	        	$('#deleteImage'+iNum).parent().remove();
	        }else{
	        	$('.beforeSubmitImage').remove();
	        	$('#deleteImage'+iNum).show();
	        }
	    });
	}
    return false;
}
function deleteFile(action, sID, item_id, iNum){
	if(confirm('Вы желаете удалить?')) {
		$('#'+sID).parent().append(beforeSubmitImage);
		$('#'+sID).hide();
		$.post(action,{id: item_id, num: iNum}, function(data){
	        if(data == '1'){
	        	$('#'+sID).parent().remove();
	        }else{
	        	$('.beforeSubmitImage').remove();
	        	$('#'+sID).show();
	        }
	    });
	}
    return false;
}

$(document).ready(function() {
	// Форма добавления/редактирования статьи
	if($('#articleForm').length){
		$('#articleForm').ajaxForm({
			target: '#articleForm',
        	dataType: 'json',
        	iframe: true,
 			beforeSubmit: beforeSubmitForm,
        	success: responseSubmitForm
		});
	}
	
    $("#loginForm").ajaxForm({
    	beforeSubmit: function(){
			$('#login').hide().after(beforeSubmitImage);
			$("#loginMessages").html('').hide();
			
		},
    	success: function(data){
			if(data.error){
				$('#beforeSubmitImage').hide();
				$('#login').show();
				$("#loginMessages").append("<span>"+ data.error +"</span>").slideDown(500);
			}else if(data.message == 'ok'){
				$('#loginBox').html(data.inner);
			}
    	},
    
    	dataType: 'json'
    });
    
    if($('.fancy').length) {
    	$(".fancy").tooltip({ 
    		track: true, 
    	    delay: 0, 
    	    showURL: false, 
    	    fade: 250 
    	}); 
    }
    if($('a.data_box').length) {
    	$("a.data_box").fancybox({
    		zoomSpeedIn: 100,
    		zoomSpeedOut:100,
    		hideOnContentClick: false
    	}); 
    }
    
}); 
if($('input.hasDatepicker').length){
jQuery(function($){
	$.datepicker.regional['ru'] = {clearText: 'Очистить', clearStatus: '',
		closeText: 'Закрыть', closeStatus: '',
		prevText: '&lt;Пред',  prevStatus: '',
		nextText: 'След&gt;', nextStatus: '',
		currentText: 'Сегодня', currentStatus: '',
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
		'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
		'Июл','Авг','Сен','Окт','Ноя','Дек'],
		monthStatus: '', yearStatus: '',
		weekHeader: 'Не', weekStatus: '',
		dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
		dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
		dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
		dayStatus: 'DD', dateStatus: 'D, M d',
		dateFormat: 'dd.mm.yy', firstDay: 1, 
		initStatus: '', isRTL: false};
	$.datepicker.setDefaults($.datepicker.regional['ru']);
});
}

function ShowImgWindow(title, src, width, height) {
	obj = window.open("", "", "scrollbars=0,dialog=0,minimizable=1,modal=1,width="+width+",height="+height+",resizable=0");
	obj.document.write("<html>");
	obj.document.write("<head>");
	obj.document.write("<title>"+title+"</title>");
	obj.document.write("</head>");
	obj.document.write("<body topmargin=0 leftmargin=0 marginwidth=0 marginheight=0>");
	obj.document.write("<img src=\""+src+"\" onClick='window.close();'/>");
	obj.document.write("</body>");
	obj.document.write("</html>");
}

var brname=navigator.appName, BrVer='';
if(brname.substring(0,2)=="Mi")
 BrVer='E';
var timer = 0;
lastid = -1;

function show(id)
{
 if(!((document.all)?document.all['menu'+id]:document.getElementById('menu'+id)))
 return;
 clearTimeout(timer);
 if((id != lastid) && (lastid!=-1))
 ((document.all)?document.all['menu'+lastid]:document.getElementById('menu'+lastid)).style.visibility = 'hidden';
 hideElement("SELECT", document.getElementById('menu'+lastid));
 lastid = id;
 ((document.all)?document.all['menu'+lastid]:document.getElementById('menu'+lastid)).style.visibility = 'visible';
}

function hidden(id)
{
 if(!((document.all)?document.all['menu'+id]:document.getElementById('menu'+id)))
 return;
 showElement("SELECT");
 timer = setTimeout("if('"+id+"' == '"+lastid+"'){((document.all)?document.all['menu"+lastid+"']:document.getElementById('menu"+lastid+"')).style.visibility = 'hidden';}", 500)
}


function GetPos(el)
{
 if (!el || !el.offsetParent)return false;
 var res=Array()
 res["left"] = el.offsetLeft;
 res["top"] = el.offsetTop;
 var objParent = el.offsetParent;
 while (objParent.tagName.toUpperCase()!="BODY")
 {
 res["left"] += objParent.offsetLeft;
 res["top"] += objParent.offsetTop;
 objParent = objParent.offsetParent;
 }
 res["right"]=res["left"]+el.offsetWidth;
 res["bottom"]=res["top"]+el.offsetHeight;
 return res;
}

function hideElement(elName, Menu)
{
 if(BrVer!='E') return;
 for (i = 0; i < document.all.tags(elName).length; i++)
 {
 Obj = document.all.tags(elName)[i];
 if(!(pMenu=GetPos(Menu)))continue;
 if(!(pObj=GetPos(Obj)))continue;

 if(pObj["left"]<pMenu["right"] && pMenu["left"]<pObj["right"] && pObj["top"]<pMenu["bottom"] && pMenu["top"]<pObj["bottom"])
 Obj.style.visibility = "hidden";
 }
}

function showElement(elName)
{
 if(BrVer!='E') return;
 for (i = 0; i < document.all.tags(elName).length; i++)
 {
 obj = document.all.tags(elName)[i];
 if (!obj || !obj.offsetParent)continue;
 if(obj.style.visibility=="hidden")
 obj.style.visibility = "visible";
 }
}
/* Заказы */
function getOrderItem(iParent){
    $.post('/order/getitem/',{parent_id: iParent}, function(data){
       $('#order_item').parent().html(data);
    });
}

/* дабавление/редактирование фирмы */
function getcity(iZone_id, iDc_id){
    $.post('/region/getcityes',{zone_id: iZone_id, dc_id: iDc_id}, function(data){
       $("#dc_id").parent("dd").html(data);
    });
}

function setSphere(th) {
	var th = $(th);
	if(th.val() == 1){
		if(th.is(':checked')){
			$("#enterprise_sphere-1, #enterprise_sphere-2, #enterprise_sphere-3").parent("label").show();
		}else{
			$("#enterprise_sphere-1, #enterprise_sphere-2, #enterprise_sphere-3").parent("label").hide();
			$("#enterprise_sphere-1, #enterprise_sphere-2, #enterprise_sphere-3").attr('checked', false);
		}
	}else{
		if(th.is(':checked')){
			$("#enterprise_sphere-10").parent("label").show();
		}else{
			$("#enterprise_sphere-10").parent("label").hide();
			$("#enterprise_sphere-10").attr('checked', false);
		}
	}
	
}

