window.onload = function(){
	g_globalObject = new JsDatePick({
					useMode:1,
					isStripped:true,
					target:"div3_example",
					cellColorScheme:"armygreen",
					g_jsDatePickImagePath:"js/img/"
				});
				
	g_globalObject.setOnSelectedDelegate(function(){
		var obj = g_globalObject.getSelectedDay();
		//alert("a date was just selected and the date is : " + obj.day + "/" + obj.month + "/" + obj.year);
		var d=obj.day.toString();
		var m=obj.month.toString();
		var y=obj.year.toString();
		if(d.length==1)d='0'+d;
		if(m.length==1)m='0'+m;
		//alert(m.length+'++'+m);
		//var input = document.getElementById("outofturn");
		//var post="";
		//if(input.type=="checkbox" && input.checked) post="&outofturn=1"; else post="&outofturn=0"
		window.location="http://"+window.location.hostname+"/index.php?option=com_hello&date="+d+"."+m+"."+y;
				});
				

};
function getURLParameter (name) {
 return decodeURI((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]);
}
function in_array(needle, haystack, strict) {	// Checks if a value exists in an array
	// 
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

	var found = false, key, strict = !!strict;

	for (key in haystack) {
		if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
			found = true;
			break;
		}
	}

	return found;
}
function show_select(){



}
function print_today() {
    var now = new Date();
    var months = new Array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
    var date = ((now.getDate() < 10) ? "0" : "") + now.getDate();

    function fourdigits(number) {
        return (number < 1000) ? number + 1900 : number;
    }
    var today = date + "." + months[now.getMonth()] + "." + (fourdigits(now.getYear()));
    return today;
}
function testurl(){
str=location;
re=/list|com_hello/g;
   if (re.test(str))
      return true;
   else
      return false;
}
function echo_sel(sel){
s1='',s2='',s3='',s4='',s5='',s6='';
if (sel){
e='selected';
if(sel==1)s1=e;
if(sel==2)s2=e;
if(sel==3)s3=e;
if(sel==4)s4=e;
if(sel==5)s5=e;
if(sel==6)s6=e;
}
return '<select name="hero" id="list"><option '+s1+' value="1">Право</option><option '+s2+' value="2">Сделка 1+1</option><option '+s3+' value="3">Сделка большая</option><option '+s4+' value="4">Мена</option><option '+s5+' value="5">Юр. Лицо</option><option '+s6+' value="6">Ипотека</option></select>';
}

function echo_s_sel(sel){
switch(sel){
case '0':return ' - ';
case '1':return 'Право';
case '2':return 'Сделка 1+1';
case '3':return 'Сделка большая';
case '4':return 'Мена';
case '5':return 'Юр. Лицо';
case '6':return 'Ипотека';
default: return '';
}
}
var ta=new Array();
ta=[
'9:00-9:45',
'9:45-10:30',
'10:30-11:15',
'11:15-12:00',
'13:00-13:45',
'13:45-14:30',
'14:30-15:15',  
];
var ta2=new Array();
ta2=[
'9:00-9:45',
'9:45-10:30',
'10:30-11:15',
'11:15-12:00',
'13:00-13:45',
'13:45-14:30',
'14:30-15:15', 
];
//if(!in_array('9:45-10:15',ta))alert(1); else alert(2);
function findindex(array,item){
 for(var i in array){
        if(array[i]==item)
            return i;
    }
}
//alert(findindex(ta,'9:00-9:45'));
jQuery = jQuery.noConflict();

jQuery(document).ready(function($) {
if(testurl()){
$.get('/components/com_hello/gate.php',{ action: "checkday", date:(getURLParameter('date')!='null')?getURLParameter('date'):print_today()  },function(data) {
  if(data=='closed')$("#lock").html('<img src="/images/lock.png">');
});
$("#t1 tr").each(function(index) {
var time=$.trim($(this).find('.time').text());
if(time=='undefined' || time=='')var err=1;
if(err!=1){
ta.splice(findindex(ta,time), 1);
}

});

$("#t2 tr").each(function(index) {
var time=$.trim($(this).find('.time').text());
if(time=='undefined' || time=='')var err=1;
if(err!=1){
ta2.splice(findindex(ta2,time), 1);
}

});
add='';
if($("#islogged").val()==1)add='<td></td><td></td><td></td><td align="center"><nobr><img id="add" src="/images/add.png"></nobr></td>';

$.each(ta, function(index, value) { 
$("#t1 tr:last").after('<tr><td align="center" class="time"><nobr>'+value+'</nobr></td><td></td><td></td><td></td><td></td>'+add+'</tr>');
});
$.each(ta2, function(index, value) { 
$("#t2 tr:last").after('<tr><td align="center" class="time"><nobr>'+value+'</nobr></td><td></td><td></td><td></td><td></td>'+add+'</tr>');
});

SortTable(0,'N','t1');
SortTable(0,'N','t2');
}




//--------------------------------------------------------------------------------------------------------------------------
$('#print').click(function(){
if($("#is_sup").val()==1){
$.get("/components/com_hello/gate.php", { action: "closed", date: $("#date").val() },
   function(data){
     alert(data);
   });
} 

$('body > :not(#t1 #t2 #stream1 #stream2 #cdate)').hide();
$('#cdate').appendTo('body');
$('#stream1').appendTo('body');
$('#t1').appendTo('body');
$('#stream2').appendTo('body');
$('#t2').appendTo('body');
});
//--------------------------------------------------------------------------------------------------------------------------
$("a[href='/index.php?option=com_hello&Itemid=78']").css('color','red');
var tmp='Ближайшая свободная очередь';
$('h3').each(function(i,b){
if($(b).text()==tmp)
$(b).html('<a href="/list" style="color:#f20000">'+tmp+'</a>')
});
//--------------------------------------------------------------------------------------------------------------------------
$('#admins').click(function(){
$.get("/components/com_hello/gate.php", {action: "getadminlist"}, function(data){
	$("#dialog").html(data);
	$("#dialog").dialog({title: 'Администраторы', buttons: { "Ok": function() { $(this).dialog("close"); } } });
});
});
//--------------------------------------------------------------------------------------------------------------------------
$('#members').click(function(){
//$.get("/components/com_hello/gate.php", {action: "getadminlist"}, function(data){
$("#dialog").html('Текст');
$("#dialog").dialog({title: 'Список участников', buttons: { "Ok": function() { $(this).dialog("close"); } } });
});
//--------------------------------------------------------------------------------------------------------------------------
$("#outofturn").click(function(){
$("body").css('cursor','wait');
jQuery.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});
$.getJSON("/components/com_hello/gate.php",
  {
    action: "getListoutofturn"
  },
  function(data) {
var table="";
table="<table class=\"adminlist\">\n<thead>\n<tr>\n<th>#</th>\n<th>Какая сделка</th>\n<th>Добавлено</th>\n<th>Участник</th><th>Контакты</th>\n\n<th>Администратор</th>\n<th>Вне очереди</th>\n<th>Адрес</th>\n<th>Собственник</th>\n<th></th>\n</tr></thead>\n";
var k=0;
    $.each(data, function(i,item){
	var checked="";
	if(item.outofturn==1) var checked="checked";
			table+="<tr class=\"row"+k+"\">\n<td>"+(i+1)+"</td>\n<td>"+echo_s_sel(item.what_a_deal)+"</td>\n<td>"+item.added+"</td>\n<td>"+item.member+"</td><td>"+item.contacts+"</td>\n\n<td>"+item.administrator+"</td>\n<td align=\"center\"><input disabled type=\"checkbox\" "+checked+"></td>\n<td>"+item.adress+"</td>\n<td>"+item.fio_ltd+"</td>\n<td><nobr><!--<img id=\"edit\" title=\""+item.id+"\" src=\"/images/edit.png\">&nbsp;--><img id=\"del\" title=\""+item.id+"\" src=\"/images/del.png\"></nobr></td>\n</tr>\n";
		k=1-k;
    });
	table+="</table>";
	$("#dialog").html("");
	$("#dialog").html(table);
	$("#dialog").dialog({title: 'Вне очереди', buttons: { "Ok": function() { $(this).dialog("destroy"); } }, width: 800,height: 300  });
	$("body").css('cursor','auto');
  });
  
});

$("#myout").click(function(){
$("body").css('cursor','wait');
jQuery.ajaxSetup({ scriptCharset: "utf-8" , contentType: "application/json; charset=utf-8"});
if($("#hname").val()!='')
$.post("/components/com_hello/gate.php",
  {
    action: "myout",
	admin: $("#hname").val()
  },
  function(data) {
var table="";
table="<table class=\"adminlist\">\n<thead>\n<tr>\n<th>#</th>\n<th>Добавлено</th>\n<th>Дата</th>\n<th>Время</th>\n<th>Какая сделка</th>\n<th>Участник</th>\n<th>Контакты</th>\n<th>Администратор</th>\n<th>Адрес</th>\n<th>Собственник</th>\n<th>Поток</th>\n<th>Вне очереди</th>\n<th></th>\n</tr></thead>\n";
var k=0;
    $.each(data, function(i,item){
	var checked="";
	if(item.outofturn==1) var checked="checked";
			table+="<tr class=\"row"+k+"\">\n<td>"+(i+1)+"</td>\n<td>"+item.added+"</td>\n<td>"+item.date+"</td>\n<td>"+item.time+"</td><td>"+echo_s_sel(item.what_a_deal)+"</td>\n\n<td>"+item.member+"</td>\n<td>"+item.contacts+"</td>\n<td>"+item.administrator+"</td>\n<td>"+item.adress+"</td>\n<td>"+item.fio_ltd+"</td>\n<td align=\"center\">"+(parseInt(item.stream)+1)+"</td>\n<td align=\"center\"><input disabled=\"disabled\"type=\"checkbox\" "+checked+"></td>\n<td><nobr><!--<img id=\"edit\" title=\""+item.id+"\" src=\"/images/edit.png\">&nbsp;--><img id=\"del\" title=\""+item.id+"\" src=\"/images/del.png\"></nobr></td>\n</tr>\n";
		k=1-k;
    });
	table+="</table>";
	$("#dialog").html("");
	$("#dialog").html(table);
	$("#dialog").dialog({title: 'Моя очередь', buttons: { "Ok": function() { $(this).dialog("destroy"); } }, width: 1100,height: 500  });
	$("body").css('cursor','auto');
  },"json");
});

$("#add").live('click',function(){
var curdate=(getURLParameter('date')!='null')?getURLParameter('date'):print_today();
var time=$(this).parent().parent().parent().children('.time').children().text();
var stream=$(this).parents('table').attr('id');
stream=(stream=='t1')?'0':1;

var ok=false;
$.get('/components/com_hello/gate.php',{ action: "caniadd",date:curdate },function(data) {
if(data=='ok')ok=true;
else
  alert(data);
  
 if(ok!=false){

var table="";
table="<table id=\"addtbl\" class=\"adminlist\">\n<thead>\n<tr>\n<th>Дата</th>\n<th>Время</th>\n<th>Какая сделка</th>\n<th>Участник</th>\n<th>Контакты</th>\n<th>Адрес</th>\n<th>Собственник</th>\n<th>Поток</th>\n<th>Вне очереди</th>\n</tr></thead>\n";
table+="<tr>\n<td><input class=\"text_area\" name=\"date\" size=\"10\" value=\""+curdate+"\"  disabled=\"disabled\"></td>\n<td><nobr><input  size=\"11\" class=\"text_area\" name=\"time\" value=\""+time+"\" disabled=\"disabled\"><input class=\"text_area\" name=\"allowtime\" disabled type=\"checkbox\"></nobr></td><td>"+echo_sel()+"</td>\n\n<td><input class=\"text_area\" name=\"member\"></td>\n<td><input class=\"text_area\" name=\"contacts\"></td>\n<td><input class=\"text_area\" name=\"adress\"></td>\n<td><input class=\"text_area\" name=\"fio_ltd\"></td>\n<td align=\"center\">"+(parseInt(stream)+1)+"</td>\n<td align=\"center\"><input class=\"text_area\" name=\"outofturn\" type=\"checkbox\"></td>\n</tr>\n";
table+="</table>";
$('input[name="outofturn"]').live('change',function(){
if($(this).is(':checked'))$('input[name="allowtime"]').attr("checked",true).removeAttr("disabled");
else $('input[name="allowtime"]').attr("disabled",true).attr("disabled",true);
});
$('input[name="allowtime"]').live('change',function(){
if($(this).is(':checked'))$('input[name="time"]').show(300);
else $('input[name="time"]').hide(300);
});
	$("#dialog").html("");
	$("#dialog").html(table);
	$("#dialog").dialog({title: 'Добавить', buttons: { "Сохранить": function() { ajaxadd($('input[name="allowtime"]').is(':not(:checked)'),curdate,time,$("#list option:selected").val(),$('input[name="fio_ltd"]').val(),$('input[name="contacts"]').val(),$('input[name="adress"]').val(),$('input[name="member"]').val(),stream,$('input[name="outofturn"]').is(':checked')) },"Отмена": function() { $(this).dialog("destroy");$("#dialog").html(""); } }, width: '95%',height: 300  });
	if($('input[name="outofturn"]').is(':not(:checked)'))$('input[name="allowtime"]').attr("checked",true);
}	
});

});
/////////////////////////////////////////////
$("#edit").live('click',function(){
$("body").css('cursor','wait');
//var curdate=(getURLParameter('date')!='null')?getURLParameter('date'):print_today();
var _id=$(this).attr('title');
$.getJSON('/components/com_hello/gate.php',{ action: "get", id:_id },function(data) {
var table="";
var checked='';
if(data[0].outofturn==1)checked="checked";
table="<table id=\"edtbl\" class=\"adminlist\">\n<thead>\n<tr>\n<th>Дата</th>\n<th>Время</th>\n<th>Какая сделка</th>\n<th>Участник</th>\n<th>Контакты</th>\n<th>Администратор</th>\n<th>Адрес</th>\n<th>Собственник</th>\n<th>Поток</th>\n<th>Вне очереди</th>\n</tr></thead>\n";
table+="<tr>\n<td><input class=\"text_area\" name=\"date\" size=\"10\" value=\""+data[0].date+"\"  disabled=\"disabled\"></td>\n<td><nobr><input  size=\"11\" class=\"text_area\" name=\"time\" value=\""+data[0].time+"\" disabled=\"disabled\"><input class=\"text_area\" name=\"allowtime\" disabled type=\"checkbox\"></nobr></td><td>"+echo_sel(data[0].what_a_deal)+"</td>\n\n<td><input class=\"text_area\" name=\"member\" value=\""+data[0].member+"\"></td>\n<td><input class=\"text_area\" name=\"contacts\" value=\""+data[0].contacts+"\"></td>\n<td><input disabled class=\"text_area\" name=\"administrator\" value=\""+data[0].administrator+"\"></td>\n<td><input class=\"text_area\" name=\"adress\" value=\""+data[0].adress+"\"></td>\n<td><input class=\"text_area\" name=\"fio_ltd\" value=\""+data[0].fio_ltd+"\"></td>\n<td align=\"center\" name=\"stream\">"+(parseInt(data[0].stream)+1)+"</td>\n<td align=\"center\"><input class=\"text_area\" name=\"outofturn\" type=\"checkbox\" "+checked+"></td>\n</tr>\n";
table+="</table>";
$('input[name="outofturn"]').live('change',function(){
if($(this).is(':checked'))$('input[name="allowtime"]').attr("checked",true).removeAttr("disabled");
else $('input[name="allowtime"]').attr("disabled",true).attr("disabled",true);
});
$('input[name="allowtime"]').live('change',function(){
if($(this).is(':checked'))$('input[name="time"]').show(300);
else $('input[name="time"]').hide(300);
});
$("#dialog").html("");
$("#dialog").html(table);
$("#dialog").dialog({title: 'Редактировать', buttons: { "Сохранить": function() { ajaxedit($('input[name="date"]').val(),$('input[name="allowtime"]').is(':not(:checked)'),_id,$('input[name="time"]').val(),$("#list option:selected").val(),$('input[name="fio_ltd"]').val(),$('input[name="contacts"]').val(),$('input[name="adress"]').val(),$('input[name="member"]').val(),$('input[name="outofturn"]').is(':checked')); },"Отмена": function() { $(this).dialog("destroy");$("#dialog").html(""); } }, width: '95%',height: 300  });
$("body").css('cursor','auto');
if($('input[name="outofturn"]').is(':not(:checked)'))$('input[name="allowtime"]').attr("checked",true);
},"json");

});
/////////////////////////////////////////////
var ajaxedit=function(date,allowtime,id,time,what_a_deal,fio_ltd,contacts,adress,member,outofturn){
outofturn=(outofturn==true)?1:0;
time=(allowtime==true)?'':time;
//alert(what_a_deal+' - '+fio_ltd+' - '+contacts+' - '+adress+' - '+member+' - '+outofturn);
jQuery.ajaxSetup({ scriptCharset: "utf-8" , contentType: "charset=utf-8"});
$.post("/components/com_hello/gate.php", {date:date,time:time,id:id,action:"edit",what_a_deal:what_a_deal,fio_ltd:fio_ltd,contacts:contacts,adress:adress,member:member,outofturn:outofturn},
   function(data) {
     alert(data);
	 location.reload();
});
}
var ajaxadd=function(allowtime,date,time,what_a_deal,fio_ltd,contacts,adress,member,stream,outofturn){
time=(allowtime==true)?'':time;
outofturn=(outofturn==true)?1:0;
//alert(date+' - '+time+' - '+what_a_deal+' - '+fio_ltd+' - '+contacts+' - '+adress+' - '+member+' - '+stream+' - '+outofturn);
jQuery.ajaxSetup({ scriptCharset: "utf-8" , contentType: "charset=utf-8"});
$.post("/components/com_hello/gate.php", {admin:$("#hname").val(),action:"add",date:date,time:time,what_a_deal:what_a_deal,fio_ltd:fio_ltd,contacts:contacts,adress:adress,member:member,outofturn:outofturn,stream:stream},
   function(data) {
     alert(data);
	 location.reload();
});
}

$('#del').live('click',function(){
jQuery.ajaxSetup({ scriptCharset: "utf-8" , contentType: "charset=utf-8"});
if (confirm('Are you sure?'))
$.get('/components/com_hello/gate.php',{ action: "del", id:$(this).attr('title')  },function(data) {
  alert(data);
  location.reload();
});
});

});

