﻿/*
 *
 *
 *
 */
(function($) { 
$.chatRequester = function(options) {
     this.options = $.extend({}, $.chatRequester.DEFAULTS, options || {});  
	 this.cur = this.options.timeout/1000;
	 this.timer = 0;
	 this.step = 0;
	 this.id = this.options.to;
	 var content = '<div class="request_poster">';
	 if(this.options.sellername != "" ) 
	    content += '<div class="approve"><h3>Contacting party: '+ this.options.sellername +'</h3>';
     else 
        content += '<div class="approve"><h3>Contacting your party:</h3>';
     
     content += '<div class="countdown"><p style="padding-top:25px;margin:0;">05:00</p></div><br /></div></div>';
     var self = this;
     this.win = new Boxy(content, { title: 'Contacting ... ' + this.options.sellername,beforeUnload:function(){  
           if(chat.indexOfRequester(self.options.to)>=0)
           	       chat.removeRequester(self.options.to);
	       if( $('#LiveChatLink_'+self.options.context).length>0)
	           $('#LiveChatLink_'+self.options.context).html("<img src='/im/images/livechat.png' alt='' />");
	       return true;
	 }});
	 
	 if(this.options.forcedRequest) 
	    this.win.hide();

	 if(this.step == 0 ){
	   this.postRequest();  
	   this.step = 1;
	 }	
};
$.extend($.chatRequester, {    
    DEFAULTS: { timeout:300000, to:'',context:'',   sellername:'',   forcedRequest:false }
});

$.chatRequester.prototype= {
	setSellerName: function(pSellerName){
	    this.SellerName = pSellerName;
	},
	
	wait:function(planid){
	   this.context = planid;
	   if(this.step == 0){   this.postRequest(); }
	   this.step =2;
	},
	
    countDown:function(){
      clearTimeout(this.timer);
      if(!this.win) return;
      var ct = this.win.getContent().find(".countdown");
      if(ct.length<1){clearTimeout(this.timer); return;}
      else {
	     var strSecond = (this.cur -Math.floor(this.cur/60) *60);
	     strSecond = leftFill( strSecond, 2);
	     ct.html(Math.floor(this.cur/60) + ":" + strSecond);   
	  }
	  var self = this;
      this.cur --;
      if(this.cur <0 ){
        this.cur = 0;
        this.step = 0;
        
        if(true) 
            this.onPartyOffline();
        else{
            var content = '<div class="approve">Your party has not responded. ';
            content += ' You can leave a message bellow:<br /><textarea></textarea><br /><input type="button" value="send" />';
            content += '</div>';
            
            self.win.setContent(content);
            
            input.keypress(function(e){self.stopCount();  });
            send.click(function(e){ self.sendMessage();  }); 
            this.timer = setTimeout(function(){self.close();},10000);
        }
      }else{         
         this.timer = setTimeout(function(){self.countDown();},1000);
      }        
    },
       
    
    stopCount:function(){
     clearTimeout(this.timer);
    },
    
    close:function(){
        clearTimeout(this.timer);
        this.win.unload();
        chat.removeRequester(this.to);
    },
	
	postRequest:function(){
	   var params = {action:"ping",context:this.options.context,to:this.options.to,from:this.options.from};
       if(this.channel != null)
        params.channel=this.channel;
       var self = this;
        this.countDown();
       if(this.options.type == 0)
          $.post("/lt.ashx",params, function(res) { self.onRequestSent(res); },  'json');
       else
         $.post("/lt.ashx",params, function(res) { self.onRequestSent(res); },  'json');
	},
	
	onRequestSent:function(res){
	    if(res.status == 99){
	        this.onPartyOffline();
	    }else if(res.status == 1){
	        this.countDown();
	    }else if(res.status == 2){
	        chat.showSelector(res.msg);
	    }else if(res.status == -1){
	        this.win.close();
	        alert(res.msg);
	    }else alert(res.msg);
	},
	
	onPartyOffline:function(){
	   var empty = "Enter date and time";
	   var content = '<div class="approve">';
	   content +='<p style="width:420px;">The other party seems to be away right now, please leave a brief message and specify ';
	   content += 'when you will be available to try again with a Live Transfer chat</p>';
	   content += '<ul class="login" >';
	   content += '<li><label>>>My Message:</label><textarea rows="3" class="message1"></textarea></li>';
	   content += '<li><label>>>I will be available at:</label> <input class="appinput" type="text" style="float:left;" value="'+empty+'" /></li>';
	   content += '<li style="clear:left"><b style="color:red" class="appdate">Type a date and time above. eg "Tomorrow at 5pm" or "Next Sunday at 11am</b>. </li>';
	   content += '<li><a class="appconfirm" href="javascript:void(0);" ><img class="imgconfirm" src="/images/send.png" alt="" /></a>';
	   content += '<input type="hidden" name="message" class="appmessage" />';
	   content += '<input type="hidden" name="to" class="to" />';
	   content += '<input type="hidden" name="pid" value="'+this.options.context+'" />';
	   content += '</li></ul></div>';
	  this.win.setContent(content);
	  this.stopCount(); 
	  var self = this;
	  var input = self.win.getContent().find(".appinput");
	  var date = null;
	  input.keyup(function(e){
	        var date_string = self.win.getContent().find(".appdate");
            date_string.removeClass("accept").removeClass("empty");
            if (input.val().length > 0) {
               date = Date.parse(input.val());
            if (date !== null) {
                input.removeClass("accept");
                date_string.addClass("accept");
                var gmt = date.getUTCOffset().substring(0,3);
                if(gmt.substring(1,1) == 0) gmt = gmt.replace("0","");
                date_string.html(date.toString('dddd MMMM d') + 'th at '+ date.toString('htt') +'(GMT'+gmt+')');
                self.win.getContent().find(".appmessage").val( date_string.html());
            } else {
               input.addClass("validate_error");
               date_string.addClass("error").html("Wrong format.");
                self.win.getContent().find(".appmessage").val("");
        }
        } else {
           date_string.addClass("empty").html('Type a date above. eg "Tomorrow at 5pm" or "Next Sunday at 11am');
         }
	  }).focus(function(e){input.val(''); }).blur(function(e){input.val(''); });
	  
	 self.win.getContent().find(".appconfirm").click(function(e){
         if (date == null) {
	        alert("Please input your date and time");
	        return;
	     }
         var f = self.win.getContent();
         var msg = {app:1,message1:f.find(".message1").val(),message:f.find(".appmessage").val(),to:self.options.to,pid:self.options.context}
	     $.postJSON('/service/message.ashx',msg,
             function(rs){
                if(rs.success) alert('Your message has sent');
                else alert(rs.message);
            });
	   } );
	},
	
	sendMessage:function(){
	   var toUser = chat.friends.member(this.to);
	   var pid = typeof(toUser.Plans)!='undefined'?chat.friends.member(this.to).Plans[0].ID:"";
	   var params = {action:"leavemessage",to:this.to,planid:pid,message:this.win.getContent().find("textarea").val()}
       if(this.to != null) params.push("to="+this.to);
        $.postJSON('/service/message.ashx',params,
             function(rs){
                if(rs.success) alert('Your message has sent');
                else alert(rs.message);
         });

       this.close();
	},
	
	close:function(){
	   if(this.win)
	   	   this.win.unload();
	   this.win = false;
	},
	
	onRejected:function(){
	    this.win.getContent().update('<div class="center" style="padding:10px;"><h3>Your party has rejected.</h3></div>');
		this.win.setTitle('Rejected...');
        $.title ("Your party has rejected!");
	}
}

})(jQuery);	