var is_archive_uploading = 0;
//alert("mozilla: " + browser.mozilla + "\nchrome: " + browser.chrome);

function delClient(id) {
  var hndl_delClient = function(obj, text) {
    window.location = '/admin.php?act=list';
  }
  var fail_delClient = function(obj, text) {
    alert('По неизвестной причине клиент не может быть удален.');
  }
  Ajax.Post({url: '/admin.php',
            query: {'act': 'c_del', 'id': id},
            onDone: hndl_delClient,
            onFail: fail_delClient});
}

function sendEmail() {
  var handle_sendEmail = function(obj, text) {
    ge('login').style.display = "none";
    ge('check_text').innerHTML = '<p><label>Вы подписаны на рассылку уведомлений о новых фотографиях в интересующей Вас галереи.<br /><label></p><p class="submit"><input type="button" value="Ок" tabindex="100" onclick="window.location = \'http://visualwedding.ru\';"></p>';    
    ge('login').style.display = "block";
  }
  var fail_sendEmail = function(obj, text) {
    alert("По неизвестным причинам невозможно подписаться!");
  }  
  Ajax.Post({url: '/photos.php',
            query: {'act': 'n_email',
                    'pin': ge('pin').value,
                    'n_email': ge('n_email').value},
            onDone: handle_sendEmail,
            onFail: fail_sendEmail});
}

function checkClient() {
  var hndl_checkClient = function(obj, text) {
    //alert(text);
    /* pin is correct, gallery is ready */
    //alert(text);
    if (text.substr(0, 1) == '1') {
      window.location = text.substr(1);
    }
    /* pin is correct, gallery is not ready */
    if (text.substr(0, 1) == '0') {
      ge('login').style.display = "none";
      ge('check_text').innerHTML = text.substr(1);
      //ge('pin').style.display = "none";
      //ge('submit').innerHTML = '<input type="button" value="Ок" tabindex="100" onclick=onclick="sendEmail();">'
      ge('login').style.display = "block";
    }
    /* pin is incorrect */
    if (text.substr(0, 1) == '-'){
      ge('login').style.display = "none";
      ge('check_text').innerHTML = '<p><label>Введенный пин-код неверен! Попробуйте снова и будьте внимательны!<br /><input type="text" id="pin" class="input" value="" maxlength="8" /><label></p><p class="submit"><input type="button" value="Готово" tabindex="100" onclick="checkClient();">	</p>';
      ge('login').style.display = "block";
    }
  }
  var fail_checkClient = function(obj, text) {}
  Ajax.Post({url: '/photos.php',
            query: {'act': 'c_check', 'pin': ge('pin').value},
            onDone: hndl_checkClient,
            onFail: fail_checkClient});
}

var createClient = function() {
  var hndl_createClient = function(obj, text) {
    window.location = '/admin.php?act=edit&id='+text;
  }
  var fail_createClient = function(obj, text) {
    alert("По неизвестным причинам невозможно добавить нового клиента.");
  }
  if (ge('client_name').value == '') {
    ge('box_message_body').innerHTML = 'Имя клиента не может быть пустым.';
    box_show('box_message');
  } else {
    Ajax.Post({url: '/admin.php',
            query: {'act': 'c_create',
                    'name': ge('client_name').value},
            onDone: hndl_createClient,
            onFail: fail_createClient});
  }
}

var createUser = function() {
  var hndl_createUser = function(obj, text) {
    window.location = '/admin.php?act=user_edit&id='+text;
  }
  var fail_createUser = function(obj, text) {
    alert("По неизвестным причинам невозможно добавить нового юзера.");
  }
  Ajax.Post({url: '/admin.php',
            query: {'act': 'c_user_create',
                    'email': ge('user_email').value,
                    'pass': ge('user_pass').value},
            onDone: hndl_createUser,
            onFail: fail_createUser});
}

var uploadPhotos = function() {
  var hndl_uploadPhotos = function(obj, text) {
    ge('box_upload_step3_text').innerHTML = 'Проверьте список загруженных файлов:<br /><textarea cols="44" rows="3">'+text+'</textarea>';
  }
  var fail_uploadPhotos = function(obj, text) {
    alert("По неизвестным причинам невозможно произвести загрузку фотографий.");
  }
  ge('box_upload_step3_text').innerHTML = 'Фотографии загружаются, ждите.<br /><div align="center"><img src="/images/upload.gif"></div>';
  box_show('box_upload_step3');
  Ajax.Post({url: '/admin.php',
            query: {'act': 'c_upload',
                    'id': ge('id').value},
            onDone: hndl_uploadPhotos,
            onFail: fail_uploadPhotos});
}

var updateClient = function(act) {
  var hndl_updateClient = function(obj, text) {
    if(act == 'save') {
      window.location = '/admin.php?act=list';
    }
  }
  var fail_updateClient = function(obj, text) {
    alert("По неизвестным причинам невозможно обновить информацию.");
  }
  if (ge('name').value == '') {
    ge('box_message_body').innerHTML = 'Имя клиента не может быть пустым.';
    box_show('box_message');
  } else {  
  Ajax.Post({url: '/admin.php',
            query: {'act': 'c_edit',
                    'id': ge('id').value,
                    'pin': ge('pin').value,
                    'name': ge('name').value,
                    'day_w': ge('day_w').value,
                    'month_w': ge('month_w').value,
                    'year_w': ge('year_w').value,
                    'day_d': ge('day_d').value,
                    'month_d': ge('month_d').value,
                    'year_d': ge('year_d').value,                    
                    'link': ge('link').value,
                    'status': ge('status').value,
                    'slideshow': ge('slideshow').value},
            onDone: hndl_updateClient,
            onFail: fail_updateClient});
  }
}

function updateUser(act) {
  var hndl_updateUser = function(obj, text) {
    if(act == 'save') {
      window.location = '/admin.php?act=list';
    }
  }
  var fail_updateUser = function(obj, text) {
    alert("По неизвестным причинам невозможно обновить информацию.");
  }  
  Ajax.Post({url: '/admin.php',
            query: {'act': 'c_user_edit',
                    'id': ge('id').value,
                    'prof': ge('prof').value,
                    'name': ge('name').value,
                    'blog': ge('blog').value,
                    'vkontakte': ge('vkontakte').value},
            onDone: hndl_updateUser,
            onFail: fail_updateUser});
}

function noticeShow(subject, to, cc, bcc, body) {
  //alert('mailto:'+to+'?subject='+subject+'&cc='+cc+'&bcc'+bcc+'&body='+body);
  //window.location = 'mailto:'+to;
	ge('mail_to').value = to;
	ge('mail_cc').value = cc;
	ge('mail_bcc').value = bcc;
	ge('mail_subject').value = subject;
	ge('mail_body').value = body;
	box_show_x('box_notice_send', 600, 520);
}

function noticeSend() {
  var hndl_noticeSend = function(obj, text) {
	  //alert(text);
    box_hide('box_notice_send');
  }
  var fail_noticeSend = function(obj, text) {
    alert("Неизвестная ошибка.");
  }  
  Ajax.Post({url: '/admin.php',
            query: {'act': 'c_notice_send',
                    'to': ge('mail_to').value,
                    'cc': ge('mail_cc').value,
                    'bcc': ge('mail_bcc').value,
                    'subject': ge('mail_subject').value,
                    'body': ge('mail_body').value},
            onDone: hndl_noticeSend,
            onFail: fail_noticeSend});
}

function hndl_upload_archive() {
  if(browser.mozilla || browser.chrome) {
		if(ge('rmv').value == 'on') {
			Ajax.Post({url: '/admin.php',
							query: {'act': 'c_empty_gallery',
											'id': ge('id').value},
							onDone: function() {ge('files_status').innerHTML = "Все фотографии в галерее удалены"; if(files.length > 0) handle_files(file_index);},
							onFail: function() {}});
		} else {
			if(files.length > 0) handle_files(file_index)
			else ge('files_status').innerHTML = "Фотографии для загрузки не выбраны";
		}
	}	else {
		is_archive_uploading = 1;
		ge('form_upload_archive').submit();
		box_hide('box_upload_archive');
		ge('box_message_body').innerHTML = 'Архив с фотографиями загружается и обрабатывается, ждите.<br><div align="center"><img src="/images/upload.gif"></div>';
		box_show('box_message');
	}
	
	return false;
}

function hndl_onload_frame_upload_archive() {
  if (is_archive_uploading == 1) {
    is_archive_uploading = 0;
    box_hide('box_message');
    var iframe = ge('frame_upload_archive'); 
    var doc = iframe.contentDocument || iframe.contentWindow; 
    if (doc.document) doc = doc.document;
    /* Successfully upload photos */
    if (doc.body.innerHTML.substr(0, 1) == '1') {
      ge('box_message_body').innerHTML = 'Следующие фотографии успешно добавлены в галерею:<br /><textarea cols="43" rows="3" readonly>'+doc.body.innerHTML.substr(1)+'</textarea>';
    } else {
      ge('box_message_body').innerHTML = 'Во время загрузки фотографий произошла ошибка:<br /><span style="color: red;">&laquo;'+doc.body.innerHTML.substr(1)+'&raquo;</span>';
    }
    box_show('box_message');   
  }
}

function h() {
	//get the input and UL list 
	var input = document.getElementById('file_list'); 
	var list = document.getElementById('file_list_print'); 
	var text;
	//for every file... 
	text = '';
	for (var i = 0; i < input.files.length; i++) { 
		//add to list 
		text = text + input.files[i].name + '<br />'; 
	}
	list.innerHTML = text;
}

