var create_box;
var check_box;
var warning_box;
var is_client = 0;

var on_send_email = function() {
  var handle_send_email = function(obj, text) {
    warning_box.hide();
    warning_box.content('<div style="text-align: center; margin-bottom: 5px">Вы подписаны на рассылку уведомлений о новых фотографиях в интересующей Вас галереи.</div>' + text);
    warning_box.removeButtons();
    warning_box.addButton({label: 'Ok', onClick: function() {warning_box.hide(); document.location = "http://www.alexfomin.ru/";}});
    warning_box.show();
  }
  Ajax.Post({url: '/clients.php',
            query: {'act': 'n_email', 'pin': ge('pin').value, 'n_email': ge('n_email').value},
            onDone: handle_send_email,
            onFail: handle_send_email});
}

var on_checkClient = function() {
  var hndl_checkClient = function(obj, text) {
    //alert(text);
    /* pin is correct, gallery is ready */
    if (text.substr(0, 1) == '1') {
     check_box.hide();
     window.location = text.substr(1);
    }
    /* pin is correct, gallery is not ready */
    if (text.substr(0, 1) == '0') {
      check_box.hide();
      warning_box.removeButtons();
      warning_box.addButton({label: 'Отмена', style: 'button_no', onClick: function() {warning_box.hide(); document.location = "http://www.alexfomin.ru/";}});
      warning_box.addButton({label: 'Оставить e-mail', onClick: on_send_email});      
      warning_box.content(text.substr(1));
      warning_box.show();
      ge('n_email').focus();
    }
    /* pin is incorrect */
    if (text.substr(0, 1) == '-'){
      check_box.hide();
      warning_box.removeButtons();
      warning_box.addButton({label: 'Ок', onClick: function() {warning_box.hide(); ge('pin').value = ''; check_box.show(); ge('pin').focus();}});
      warning_box.content('<div style="text-align: center; margin-bottom: 5px">Введенный пин-код неверен! Попробуйте снова и будьте внимательны!</div>');
      warning_box.show();
    }
  }
  Ajax.Post({url: '/clients.php',
            query: {'act': 'c_check', 'pin': ge('pin').value},
            onDone: hndl_checkClient,
            onFail: check_box.show});
}

function checkClient() {
  check_box.removeButtons();
  check_box.addButton({label: 'Отмена', style: 'button_no', onClick: check_box.hide});
  check_box.addButton({label: 'Ок', onClick: on_checkClient});
  check_box.content('<div style="text-align: center;"><div style="margin-bottom: 5px">Введите пин-код, написанный на вашей визитке:</div><input id="pin" name="pin" type="text" maxlength="10" style="width: 70px; margin: 3px 0px 0px;"/></div>');
  check_box.show();
  ge('pin').focus();
}

function updateOpacity(id, opacity, delay) {
  opacity = opacity - 0.1;
  ge(id).style.opacity = opacity;
  alert(ge(id).style.opacity);  
  if(ge(id).style.opacity > 0) setTimeout("updateOpacity(id, opacity, delay)", delay);
}

var delClient = function(cid) {
  var hndl_delClient = function(obj, text) {}
  var fail_delClient = function(obj, text) {
    ge('client_'+cid).style.opacity = 1.0;
    show(ge('clnt_b_'+cid).getElementsByTagName('div')[0]);
    show(ge('clnt_a_'+cid).getElementsByTagName('div')[0]);
    ge('clnt_b_'+cid).getElementsByTagName('span')[0].innerHTML = '';
  }
  Ajax.Post({url: '/clients.php',
            query: {'act': 'c_delete', 'cid': cid},
            onDone: hndl_delClient,
            onFail: fail_delClient});
}

var on_remClient = function(cid) {
  var hndl_remClient = function(obj, text) {
    ge('client_'+cid).style.background = "#FEFAE4 none repeat scroll 0 0";
    ge('clnt_b_'+cid).getElementsByTagName('span')[0].innerHTML = "<b style='font-weight:normal; color:#908851'>Клиент удален</b>";
    ge('clnt_a_'+cid).getElementsByTagName('span')[0].innerHTML = "<a href='javascript:resClient(" + cid + ")'>Отмена</a>";
    //setTimeout("updateOpacity('client_'+cid, 1.0, 1000)", 1);
    var o = 1.0
    setTimeout(function()
      {
        // client still removed */
        if(ge('client_'+cid).getElementsByTagName('span')[0].innerHTML != '')
        {
          o = o - 0.1;
          ge('client_'+cid).style.opacity = o;
          if (o > 0)
          {
            setTimeout(arguments.callee, 250);
          }
          else
          {
            hide(ge('client_'+cid));
            delClient(cid);
          }
        }
      },
    5000);
  }
  var fail_remClient = function(obj, text) {
    show(ge('clnt_b_'+cid).getElementsByTagName('div')[0]);
    show(ge('clnt_a_'+cid).getElementsByTagName('div')[0]);
    ge('clnt_b_'+cid).getElementsByTagName('span')[0].innerHTML = '';
  }  
  warning_box.hide();
  hide(ge('clnt_b_'+cid).getElementsByTagName('div')[0]);
  hide(ge('clnt_a_'+cid).getElementsByTagName('div')[0]);
  ge('clnt_b_'+cid).getElementsByTagName('span')[0].innerHTML = '<img valign="middle" src="/images/upload.gif">';
  
  Ajax.Post({url: '/clients.php',
            query: {'act': 'c_remove', 'cid': cid},
            onDone: hndl_remClient,
            onFail: fail_remClient});
}

function remClient(cid, name) {
  warning_box.removeButtons();
  warning_box.addButton({label: 'Отмена', style: 'button_no', onClick: warning_box.hide});
  warning_box.addButton({label: 'Ок', onClick: function() {on_remClient(cid)}});
  warning_box.content('<div style="text-align: center; margin-bottom: 5px">Точно удалить клиента "' + name + '"?</div>');
  warning_box.show();
}

function resClient(cid) {
  var hndl_resClient = function(obj, text) {
    ge('client_'+cid).style.background = "#FFFFFF none repeat scroll 0 0";
    ge('clnt_b_'+cid).getElementsByTagName('span')[0].innerHTML = "";
    show(ge('clnt_b_'+cid).getElementsByTagName('div')[0]);
    ge('clnt_a_'+cid).getElementsByTagName('span')[0].innerHTML = "";
    show(ge('clnt_a_'+cid).getElementsByTagName('div')[0]);
  }
  var fail_resClient = function(obj, text) {
    ge('clnt_b_'+cid).getElementsByTagName('span')[0].innerHTML = "<b style='font-weight:normal; color:#908851'>Клиент удален</b>";
  }
  ge('client_'+cid).style.opacity = 1.0;
  ge('clnt_b_'+cid).getElementsByTagName('span')[0].innerHTML = '<img valign="middle" src="/images/upload.gif">';
  Ajax.Post({url: '/clients.php',
            query: {'act': 'c_restore', 'cid': cid},
            onDone: hndl_resClient,
            onFail: fail_resClient});
}

var startSiblings;

function getSiblingsIds(elem){
	var prev, next, el = elem;
	while (el.previousSibling) {
		prev = el = el.previousSibling;
		if (prev.nodeType != 3)
			break;
		prev = null;
	}
	el = elem;
	while (el.nextSibling) {
		next = el = el.nextSibling;
		if (next.nodeType != 3)
			break;
		next = null;
	}
	return [prev ? prev.id.match(/(\d+)/)[1] : 0, next ? next.id.match(/(\d+)/)[1] : 0];
}


function sortClientsInit(){
	ge('clients').onSortBegin = function(elem) {
		this.sortHelper.style.backgroundColor = "#FFFFFF";
		this.sortHelper.style.marginBottom = "5px";
		startSiblings = getSiblingsIds(elem);
		//ge("editPopup").display = "none";
	}
	ge('clients').onSortEnd = function(elem) {
		var siblings = getSiblingsIds(elem);
		if (startSiblings[0] != siblings[0] || startSiblings[1] != siblings[1]) {
			var ajax = new Ajax();
			ajax.onDone = function(){
				hide('progr');
			};
			ajax.onFail = function(){
				hide('progr');
			};      
			show('progr');
      // alert('client:'+elem.id.match(/(\d+)/)[1]+'; last:'+siblings[0]+'; next:'+siblings[1]);
			ajax.post('/clients.php', {
				act: 'c_sort',
				cid: elem.id.match(/(\d+)/)[1],
				last: siblings[0],
				next: siblings[1]
			});
		}
	} 
	sortable.makeSortable(ge('clients'), sortable.DIR_BOTH);
	for(i in ge('clients').childNodes){
		if(ge('clients').childNodes[i].id){
			ge('clients').childNodes[i].style.cursor = "move";
		}
	}
}

var on_createClient = function() {
  var hndl_createClient = function(obj, text) {
    if (text.substr(0, 1) == 'r') {
      create_box.hide();
      window.location = text.substr(1);
    } else {
      ge('new_name').focus();
    }
  }
  var fail_createClient = function(obj, text) {
    ge('new_name').focus();
  }
  Ajax.Post({url: '/clients.php',
            query: {'act': 'c_create', 'name': ge('new_name').value},
            onDone: hndl_createClient,
            onFail: fail_createClient});
}

function createClient() {
  create_box.removeButtons();
  create_box.addButton({label: 'Отмена', style: 'button_no', onClick: create_box.hide});
  create_box.addButton({label: 'Ок', onClick: on_createClient}); 
  create_box.content('<div style="text-align: center;"><div style="margin-bottom: 5px">' + 'Пожалуйста, введите имя заказчика' + ':</div><input id="new_name" name="new_name" type="text" style="width: 200px; margin: 3px 0px 0px;"/></div>');
  create_box.show();
  ge('new_name').focus();
}

onDomReady(function() {
  /* Load check box */
  check_box = new MessageBox({title: 'Вход для клиентов', width: 300});
  /* Load warning box */
  warning_box = new MessageBox({title: 'Внимание!', width: 300});
  /* Load box 'Create new client' */
  create_box = new MessageBox({title: 'Добавление нового заказчика', width: 300});
  
  if(is_client == 1) {
    checkClient();
  }
});

