var questHash='';
$(document).ready(function()
{
      if ($('#questions_user').length && $('#questions_user').attr('active')==1)
      {
          timer=setInterval("conference_update()", 5000);//conference_update()
      }
     $('#conf_question_send').click(function(e)
	{
            $(this).blur();
            var tmpArr = new Object();
            tmpArr['question']=$('#conf_question_text').val();
            tmpArr['conf_id']=$(this).attr('conf');
            $.ajax(
                    {
                        url: window.location.protocol+"//"+window.location.host+'/_conference.php',
                        type:'POST',
                        data:('add_question=' + $.toJSON(tmpArr)),
                        dataType: 'text',
                        success:    function (res)
                               {
                                    alert(res);
                               },
                        error:      function()
                               {
                                    alert("Internal error occured!");
                               }
                    });// end of ajax             
             return false;
	});

        $('.edit_answer_show').click(function(e)
        {
            $(this).blur();
            var strBoxId = $(this).attr('rel');
            if ($(this).attr('show')!=='on')
            {
               $('#'+strBoxId).show();
               $(this).attr('show','on');
               $(this).text('скрыть редактирование');
            }
            else
            {
               $('#'+strBoxId).hide();
               $(this).attr('show','off');
               $(this).text('ответить/редактировать');
            }
            return false;
        });
        $('.conf_answer_send').click(function(e)
        {
            $(this).blur();
            var qId=$(this).attr('question');
            var tmpArr = new Object();
            tmpArr['answer']=$('#conf'+qId+'_answer_text').val();
            tmpArr['question_id']=qId;
            $.ajax(
                    {
                        url: window.location.protocol+"//"+window.location.host+'/_conference.php',
                        type:'POST',
                        data:('add_answer=' + $.toJSON(tmpArr)),
                        dataType: 'text',
                        success:    function (res)
                               {
                                    //alert(res);
                                    $('#answer_'+qId).text(tmpArr['answer']);
                               },
                        error:      function()
                               {
                                    alert("Internal error occured!");
                               }
                    });// end of ajax
             $('#edit_answer_'+qId).hide();
             $('#conf_quest_'+qId).children('.edit_answer_show').attr('show','off');
             $('#conf_quest_'+qId).children('.edit_answer_show').text('ответить/редактировать');
             return false;
        });
        $('.conf_answer_del').click(function(e)
        {
            $(this).blur();
            if (confirm('Вы действительно хотите удалить этот вопрос?'))
            {
                var qId=$(this).attr('question');
                $.ajax(
                        {
                            url: window.location.protocol+"//"+window.location.host+'/_conference.php',
                            type:'POST',
                            data:('del_question=' + qId),
                            dataType: 'text',
                            success:    function (res)
                                   {
                                        //alert(res);
                                   },
                            error:      function()
                                   {
                                        alert("Internal error occured!");
                                   }
                        });// end of ajax
                 $('#edit_answer_'+qId).hide();
                 $('#conf_quest_'+qId).hide();
                 return false;
            }
            else
            {
                return false;
            }
            
        });

        $('.show_confquest').click(function(e)
        {
            $(this).blur();
            var strTop = ($(window).scrollTop()+25) + 'px';
            var strLeft = ($(window).width()/2-200) + 'px';
            var strBoxId = $(this).attr('rel');
            $('#'+strBoxId).attr('conf',$(this).attr('conf'));
            $('#'+strBoxId).css({top:strTop,left:strLeft});
            $('#'+strBoxId).show();

            return false;
        });
        $('#confquest_cancel').click(function()
        {
            $(this).blur();
            $('#'+$(this).attr('rel')).hide();
            return false;
        });
        $('#confquest_submit').click(function(e)
        {
            $(this).blur();
            var name = $('#confquest_name').val();
            var phone = $('#confquest_phone').val();
            var email = $('#confquest_email').val();
            var message = $('#conf_question_text').val();

            if(!email || email == "undefined" || !message || message == "undefined" || !email_check(email))
            {
                if(!email || email == "undefined" || !email_check(email))
                {
                        $('#confquest_email').css('border','2px solid red');
                }
                else
                {
                        $('#confquest_email').css('border','2px solid green');
                }
                if(!message || message == "undefined")
                {
                        $('#conf_question_text').css('border','2px solid red');
                }
                else
                {
                        $('#conf_question_text').css('border','2px solid green');
                }
                if(!name || name == "undefined")
                {
                        $('#confquest_name').css('border','2px solid red');
                }
                else
                {
                        $('#confquest_name').css('border','2px solid green');
                }
                request_send = false;
            }//end check params
            else
            {
                request_send = true;
            }
            if(request_send)
            {
                $('#confquestloadingimg').show();
                var tmpArr = new Object();
                tmpArr['question']=message;
                tmpArr['email']=email;
                tmpArr['conf_id']=$('#conf_question_form').attr('conf');
                tmpArr['name']=name;
                tmpArr['phone']=phone;
                $.ajax(
                {
                    url: window.location.protocol+"//"+window.location.host+'/_conference.php',
                    type:'POST',
                    data:('add_question=' + $.toJSON(tmpArr)),
                    dataType: 'text',
                    success:    function (res)
                           {
                              var strHtml='';
                              strHtml='<div id="conf_quest_'+res+'" class="pd5">';
                              strHtml+='<span style="color:#67BC39" class="t70">'+_getDate()+' '+_getTime()+'<br>'+name+'</span>';
                              strHtml+='<p style="margin-bottom: 0px; margin-top: 0px;"><b>Вопрос: </b><span id="quetion_'+res+'">'+message+'</span></p>';
                              strHtml+='<p style="padding-left:50px; margin-top: 0px;"><b>Ответ: </b><span id="answer_'+res+'"></span></p>';
                              strHtml+='<div>';
                              $('#questions_user').html($('#questions_user').html()+strHtml);

                              $('#confquestloadingimg').hide();
                              $('#confquest_cancel').click();
                           },
                    error:      function()
                           {
                                alert("Internal error occured!");
                           }
                 });// end of ajax
            }
            return false;
        });//end confquest send

        $('.in_detail').click(function(e)
        {
			$(this).blur();
            nId = $(this).attr('nId');
            $('#briefly_'+nId).hide();
            $('#in_detail_'+nId).show();
            $('#brieflycont_'+nId).removeClass('cont-menu-act');
            $('#brieflycont_'+nId).addClass('cont-menu');
            $('#in_detailcont_'+nId).removeClass('cont-menu');
            $('#in_detailcont_'+nId).addClass('cont-menu-act');
            return false;
        });
        $('.briefly').click(function(e)
        {
			$(this).blur();
            nId = $(this).attr('nId');
            $('#in_detail_'+nId).hide();
            $('#briefly_'+nId).show();
            $('#in_detailcont_'+nId).removeClass('cont-menu-act');
            $('#in_detailcont_'+nId).addClass('cont-menu');
            $('#brieflycont_'+nId).removeClass('cont-menu');
            $('#brieflycont_'+nId).addClass('cont-menu-act');
            return false;
        });
        $('.goTop').click(function(e)
        {
              $('html, body').stop().animate({
                 scrollTop: 0
              }, 1000);
              event.preventDefault();
            return false;
        });
});// end onready

function conference_update()
{
    var tmpArr = new Object();
    tmpArr['conf']=$('#questions_user').attr('conf');
    tmpArr['hash']=questHash;
    $.ajax(
            {
                url: window.location.protocol+"//"+window.location.host+'/_conference.php',
                type:'POST',
                data:('upd_questions=' + $.toJSON(tmpArr)),
                dataType: 'json',
                success:    function (res)
                       {
                            parse_questions(res);
                       },
                error:      function()
                       {
                           // alert("Internal error occured!");
                       }
            });// end of ajax
     return false;
}
function parse_questions(questions)
{
    var content=new Array();
    $.each(questions, function(i, val) {
      if ($('#conf_quest_'+val.id).length)
      {
          $('#quetion_'+val.id).text(val.question);
          $('#answer_'+val.id).text(val.answer);
      }
      else
      {
          var strHtml='';
          strHtml='<div id="conf_quest_'+val.id+'" class="pd5">';
          strHtml+='<span style="color:#67BC39" class="t70">'+_dateF("d.m.Y  H:m",val.time_quest)+'<br>'+val.user_name+'</span>';
          strHtml+='<p style="margin-bottom: 0px; margin-top: 0px;"><b>Вопрос: </b><span id="quetion_'+val.id+'">'+val.question+'</span></p>';
          strHtml+='<p style="padding-left:50px; margin-top: 0px;"><b>Ответ: </b><span id="answer_'+val.id+'">'+val.answer+'</span></p>';
          strHtml+='<div>';
          $('#questions_user').html($('#questions_user').html()+strHtml);
      }
    });
    //alert(content[0].question);
}

function show_confquestform()
        {
                var strTop = ($(window).scrollTop()+25) + 'px';
                var strLeft = ($(window).width()/2-200) + 'px';

                $('#_confquest').css('display','');
                $('#_confquestdiv').css('top',strTop);
                $('#_confquestdiv').css('left',strLeft);
                $('#_confquestcancel').css('display','');
                $('#_confquestitemid').attr('value',item_id);

                $('#_confquestcancel').click(function()
                {
                        $('#_confquest_email').css('border','2px solid silver');
                        $('#_confquest_text').css('border','2px solid silver');
                        $('#_confquestdiv').css('display','none');
                });

                return false;
        }

function _dateF ( format, timestamp ) {	// Format a local time/date
	//
	// +   original by: Carlos R. L. Rodrigues
	// +	  parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: MeEtc (http://yass.meetcweb.com)
	// +   improved by: Brad Touesnard

	var a, jsdate = new Date(timestamp ? timestamp * 1000 : null);
	var pad = function(n, c){
		if( (n = n + "").length < c ) {
			return new Array(++c - n.length).join("0") + n;
		} else {
			return n;
		}
	};
	var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
		"Thursday","Friday","Saturday"];
	var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
	var txt_months =  ["", "January", "February", "March", "April",
		"May", "June", "July", "August", "September", "October", "November",
		"December"];

	var f = {
		// Day
			d: function(){
				return pad(f.j(), 2);
			},
			D: function(){
				t = f.l();return t.substr(0,3);
			},
			j: function(){
				return jsdate.getDate();
			},
			l: function(){
				return txt_weekdays[f.w()];
			},
			N: function(){
				return f.w() + 1;
			},
			S: function(){
				return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
			},
			w: function(){
				return jsdate.getDay();
			},
			z: function(){
				return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
			},

		// Week
			W: function(){
				var a = f.z(), b = 364 + f.L() - a;
				var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;

				if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
					return 1;
				} else{

					if(a <= 2 && nd >= 4 && a >= (6 - nd)){
						nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
						return date("W", Math.round(nd2.getTime()/1000));
					} else{
						return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
					}
				}
			},

		// Month
			F: function(){
				return txt_months[f.n()];
			},
			m: function(){
				return pad(f.n(), 2);
			},
			M: function(){
				t = f.F();return t.substr(0,3);
			},
			n: function(){
				return jsdate.getMonth() + 1;
			},
			t: function(){
				var n;
				if( (n = jsdate.getMonth() + 1) == 2 ){
					return 28 + f.L();
				} else{
					if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
						return 31;
					} else{
						return 30;
					}
				}
			},

		// Year
			L: function(){
				var y = f.Y();
				return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
			},
			//o not supported yet
			Y: function(){
				return jsdate.getFullYear();
			},
			y: function(){
				return (jsdate.getFullYear() + "").slice(2);
			},

		// Time
			a: function(){
				return jsdate.getHours() > 11 ? "pm" : "am";
			},
			A: function(){
				return f.a().toUpperCase();
			},
			B: function(){
				// peter paul koch:
				var off = (jsdate.getTimezoneOffset() + 60)*60;
				var theSeconds = (jsdate.getHours() * 3600) +
								 (jsdate.getMinutes() * 60) +
								  jsdate.getSeconds() + off;
				var beat = Math.floor(theSeconds/86.4);
				if (beat > 1000) beat -= 1000;
				if (beat < 0) beat += 1000;
				if ((String(beat)).length == 1) beat = "00"+beat;
				if ((String(beat)).length == 2) beat = "0"+beat;
				return beat;
			},
			g: function(){
				return jsdate.getHours() % 12 || 12;
			},
			G: function(){
				return jsdate.getHours();
			},
			h: function(){
				return pad(f.g(), 2);
			},
			H: function(){
				return pad(jsdate.getHours(), 2);
			},
			i: function(){
				return pad(jsdate.getMinutes(), 2);
			},
			s: function(){
				return pad(jsdate.getSeconds(), 2);
			},
			//u not supported yet

		// Timezone
			//e not supported yet
			//I not supported yet
			O: function(){
			   var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
			   if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
			   return t;
			},
			P: function(){
				var O = f.O();
				return (O.substr(0, 3) + ":" + O.substr(3, 2));
			},
			//T not supported yet
			//Z not supported yet

		// Full Date/Time
			c: function(){
				return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
			},
			//r not supported yet
			U: function(){
				return Math.round(jsdate.getTime()/1000);
			}
	};

	return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
		if( t!=s ){
			// escaped
			ret = s;
		} else if( f[s] ){
			// a date function exists
			ret = f[s]();
		} else{
			// nothing special
			ret = s;
		}

		return ret;
	});
}

function _getDate() {	
	var d = new Date();
	var current_date = d.getDate();
	var current_month = d.getMonth();
	var current_year = d.getFullYear();

	return current_date + "." + current_month+ "." + current_year;
}
function _getTime() {
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();

	if (minutes < 10){
		minutes = "0" + minutes;
	}
	return hours + ":" + minutes;
}

