var openedId=0;
jQuery('document').ready(
  function($){
    jQuery('#pathToWinSoft').focusin(function(){
      var t=document.getElementById('pathToWinSoft');
      if(t.value=='Путь к софту для OS Windows') t.value='';      
    });
    jQuery('#pathToWinSoft').focusout(function(){
      var t1=document.getElementById('pathToWinSoft');
      if(t1.value=='') t1.value='Путь к софту для OS Windows';      
    }); 
    jQuery('#pathToMacSoft').focusin(function(){
      var t=document.getElementById('pathToMacSoft');
      if(t.value=='Путь к софту для OS Mac') t.value='';      
    });
    jQuery('#pathToMacSoft').focusout(function(){
      var t1=document.getElementById('pathToMacSoft');
      if(t1.value=='') t1.value='Путь к софту для OS Mac';      
    });
    jQuery('#pathToLinuxSoft').focusin(function(){
      var t=document.getElementById('pathToLinuxSoft');
      if(t.value=='Путь к софту для OS Linux') t.value='';      
    });
    jQuery('#pathToLinuxSoft').focusout(function(){
      var t1=document.getElementById('pathToLinuxSoft');
      if(t1.value=='') t1.value='Путь к софту для OS Linux';      
    });   
    jQuery('#softVers').focusin(function(){
      var t=document.getElementById('softVers');
      if(t.value=='Версия программы') t.value='';      
    });
    jQuery('#softVers').focusout(function(){
      var t1=document.getElementById('softVers');
      if(t1.value=='') t1.value='Версия программы';      
    });
    
    /* сохраням данные по софту */
    jQuery('#saveSoftData').click(function(){
    var pathToWinSoft=document.getElementById('pathToWinSoft').value;
    var pathToLinuxSoft=document.getElementById('pathToLinuxSoft').value;
    var pathToMacSoft=document.getElementById('pathToMacSoft').value;
    if(pathToWinSoft=='Путь к софту для OS Windows') pathToWinSoft='';
    if(pathToLinuxSoft=='Путь к софту для OS Linux') pathToLinuxSoft='';
    if(pathToMacSoft=='Путь к софту для OS Mac') pathToMacSoft='';
      $.post('../routs/routs.php', {type: 'options', action: 'saveSoftData', vers: document.getElementById('softVers').value, win: pathToWinSoft, linux: pathToLinuxSoft, mac: pathToMacSoft},    function(data){
       startInterval('messag');
       showMessage('Данные успешно сохранены');
      }); 
    });
    
    /* активируем поле для адресов тест-рассылки */
    jQuery('#testMail').click(function(){
      if(!testSubscr){
        testSubscr=true;
        jQuery('#testMailsForm').removeClass().addClass('showTestForm');
      }
      else{
        testSubscr=false;
        jQuery('#testMailsForm').removeClass().addClass('itemHide');
      }
      
    });
    



//create a bubble popup for each <DIV> element with class attribute as ".button"
		$('div.button').CreateBubblePopup();
		//set different position and align options for each <DIV>
		var positions = { 'bottom-center': {position: 'top', align: 'center' } };
		for(var id in positions){
			//set customized options for each bubble popup
			$('#'+id).SetBubblePopupOptions({
					position : positions[id].position,
					align	 : positions[id].align,
					tail	 : {align: positions[id].align},
					innerHtml: $("div.header").html(),
					innerHtmlStyle: {color:'#000000', 'text-align':'center'},
					themeName: 	'grey',
					themePath: 	'http://mynotifier.ru/img/jquerybubblepopup-theme',
					alwaysVisible: false,
					closingDelay: 200
				});
		}; //end loop  /**/
		
  }
);

var testSubscr=false;
var openedId=0;
function itemDo(openId){
  if(openedId!='0' && openedId!=openId) jQuery('#'+openedId).removeClass().addClass('itemHide');
  if(openedId==openId){   
     var class1=document.getElementById(openId).className;
     if(class1=='itemShow') jQuery('#'+openId).removeClass().addClass('itemHide');
     else jQuery('#'+openId).removeClass().addClass('itemShow');
  }
  else{
    jQuery('#'+openId).removeClass().addClass('itemShow');
  }
  openedId=openId;
}

function saveMail(id){   
  var newmail=document.getElementById(id).value;       
  $.post('../routs/routs.php', {type: 'options', action: 'setmail', mail: newmail}, function(data){  
   startInterval('messag');
   showMessage('Данные успешно сохранены'); 
  });  
}

function saveAdvert(id, linkId){
  var newadvert=document.getElementById(id).value;
  var linkadvert=document.getElementById(linkId).value;  
  $.post('../routs/routs.php', {type: 'options', action: 'setadvert', advert: newadvert, advertLink: linkadvert}, function(data){
   startInterval('messag');
   showMessage('Данные успешно сохранены'); 
  });
}

function sendMassMail(id){
  var message=document.getElementById('descr').value;
  var subj=document.getElementById('subj').value;
  var testMails=document.getElementById('testMailsForm').value;

  if(message==''){
    alert('Тело письма осталось пустым!');
    return;
	}
	$("#progress").fadeIn(200);
  $.post('../routs/routs.php', {'type': 'options', 'action': 'mailsending', 'text': message, 'test': testSubscr, 'subj': subj, 'testmails': testMails}, function(data){
		alert("Рассылка успешно завершена. Разослано писем: "+data);
    $("#progress").fadeOut(200);
  });

}

var intervalId;
var t=2000;
function startInterval(divId){
  object = {
     func: function(z) {
        if(z<=0) { 
          stopInterval(intervalId);
          t=2000;
          hideMessage();  
        }
        else{
          t=t-1000;          
        }
    }
  }
  intervalId=setInterval( function() { object.func.call(object, t) } , 1000);
}

function stopInterval(intervalId){           
	clearInterval(intervalId);
}

function showMessage(message){
  document.getElementById('messag').innerHTML=message;
  document.getElementById('messag').className='showMess';
}

function hideMessage(){
  document.getElementById('messag').innerHTML='';
  document.getElementById('messag').className='hideMess';
}

var activeProjId=0;
function projectCategories(projectId){
	$("#categList").html('<div style="text-align: center;"><img src="img/loader.gif" width="42" height="42" alt="loading..." style="border: none !important"></div>');
  $.post('../routs/routs.php', {'type': 'showCategories', 'projId': projectId}, function(data){
    if(activeProjId!='0') {
     document.getElementById('li_'+activeProjId).className="withArrow";
     jQuery('#categList').hide();
    }
    activeProjId=projectId;
    document.getElementById('categList').innerHTML=data;
    //$("#categList").html(data);
    jQuery('#categList').fadeIn(500);
    document.getElementById('li_'+projectId).className='activeLi';
    if(document.getElementById('div_'+projectId)) document.getElementById('div_'+projectId).className='itemShowS';
  });
}

function save_cats(projectId){
  var a=[];
  $('li.noArrow input:checked').each(function(index) {
    a[a.length]=$(this).val();
  });

 $.post('../routs/routs.php', {type: 'saveCategories', c: a, projId: projectId}, function(data){
  $("#saveButton").before("<div id=\"mess\" style=\"display:none; padding: 5px; color: green;\">Данные успешно сохранены</div>");
  $("#mess").fadeIn(500);
  $("#mess").fadeOut(1000);
  
 });
}

function checkAll(oForm, cbName, checked){
  for (var i=0; i<oForm[cbName].length; i++) {
   oForm[cbName][i].checked = checked;
  }
}

function go_href(id){
  var hrefId="href"+id;
	var v=jQuery("#"+hrefId).attr('href');
	window.open(v, '_blank');
}

function showCatName(divId){
	$('#d'+divId).fadeIn(50);
	//$('#li'+divId).attr('style', 'background-color: #DFDFDF');
}
function hidCatName(divId){
	$('#d'+divId).fadeOut(50);
	//$('#li'+divId).removeAttr('style');
}



var prg=0;
function make_subscr(){
	if($("#subj").val()=='' || $("#descr").val()==''){
	  alert('Заполните все поля: заголовок, текст.');
	  return;
	}
	if($("#testMail").is(":checked")){
	  $("#mesTitle").html('Это тестовая рассылка');
	}
	else{
	  $("#mesTitle").html('<br />');
	}

  $.post('../routs/routs.php', {'type': 'subscr', 'make': 'packing'}, function(data){
  	$("#packs").html('Итого '+data.packs+' пакетов по 50 штук в каждом <input type="hidden" id="packsAll" value="'+data.packs+'" />. <br />'+data.out);
	}, "json");
  $("#subsc").fadeIn(300);
}

function subscr_go(){
	var packsCnt=$("#packsAll").val();
	if($("#testMail").is(":checked")){
	  subscr(0);
	}
	else{
	  for(var i=0; i<packsCnt; i++){
			setTimeout("subscr("+i+");", 500)
		}
	}
}

function subscr(i){
	var diap=$("#input_"+i).val();
	$("#sb_"+i).attr('style', 'color: green;');
	var testMails='';
	if($("#testMail").is(":checked")){
		testMails=$("#testMailsForm").val();
	}
	$.post('../routs/routs.php', {'type': 'subscr', 'make': 'subscr', 'diap':diap, 'subj': $("#subj").val(), 'descr': $("#descr").val(), 'testMails':testMails}, function(data){
  	if(data=='good'){
   		$("#sb_"+i).removeAttr('style');
			$("#input_"+i).after(' <span style="color:green; font-weight: bold;">Готово!</span> ');
			prg++;
			var x=$("#packsAll").val();
			$("#prg1").html(prg+' из '+x);
			if(prg==x || testMails!='') alert('Рассылка успешно завершена!');

   	}
	});
}

function hideDiv(divId){
	$("#"+divId).fadeOut(300);
}





