﻿/*
 *
 *
 *
 */
(function($) { 
$.chatRequest = function(options) {
     this.options = $.extend({}, $.chatRequest.DEFAULTS, options || {});  
	 this.cur = this.options.timeout/1000;
	 this.id = this.options.from.Id;
     this.timer = 0;
     this.soundTimer = 0;
     this.soundTimer2 = 0;
     this.win = false;
     this.mini = '.livebar';
     this.panel = false; 
     if(chat.friends && chat.friends.onFriendSignOn)
        chat.friends.onFriendSignOn(this.options.from);
	 var content = '<div class="approve">';

     if(this.type ==2){ // this is ping from wizard
           content +='<h3 style="color:black;"> Live Transfer Opportunity! <br />Time Remaining:</h3>';
           content +=' <div class="countdown" ><span >05:00</span><br class="clear"/>';
           content += '<a href="javascript:void(0);" class="accept" >Accept</a> <small>|</small><a href="javascript:void(0);" class="reject">Reject</a> </div>';
           content += '<br /><span class="buyer"></span> '+this.options.from.Name;
           content +' has requested to chat with you for a potential Live Transfer. Here are their contract details:<br />';
           content += $.formatPlan(this.options.context);
           content += '<br class="clear"/> ';
     } else if(this.options.from.Role !="admin" ){
          if(this.options.from.Role == "visitor"){
               $.title ("Cellswapper Live Support request");
              content+= '<strong>A visitor would like to chat with you:</strong><br /> ';
              content += escape( this.options.context);
              content += '<div class="countdown"><span>05:00</span><br class="clear" />';   
              content += '<a href="javascript:void(0);" class="accept">Accept</a> | <a href="javascript:void(0);" class="reject">Reject</a></div>';
              this.mycnt=content;
              this.pop();
           }else{ 
               content +='<h3> Live Transfer Opportunity! <br />Time Remaining:</h3> ';
               content +='<div class="countdown"><span>05:00</span><br class="clear"/>';
               content += '<a href="javascript:void(0);" class="accept" >Accept</a> <small>|</small> <a href="javascript:void(0);" class="reject">Reject</a> </div>';
               content += '<br /><span class="buyer"></span><p style="width:300px"> '+this.options.from.Name+' has requested to chat with you to possibly initiate a Live Transfer of your contract.</p>';
               content += $.formatPlan(this.options.context)+'<br  class="clear"/> ';
               this.createchatpanel(content);    
          } 
       }else{
          $.title ("Cellswapper Live Support");
          content+= '<p style="padding:10px;width:250px;"><strong>Cellswapper Live Support would like to chat with you in order to better assist you.</strong><br /> </p>';
          content += '<div class="countdown"><span >05:00</span><br class="clear" />';   
          content += '<a href="javascript:void(0);" class="accept" >Accept</a> | <a href="javascript:void(0);" class="reject">Reject</a></div>';
          this.mycnt=content;
          this.pop();
       }
       
       content += "</div>";
       
       this.mycnt=content;
       var self = this;
	     
       if(chat.playSound && chat.playSoundOnRequest){ 
	   	   playSound("request");
	   	   this.soundTimer = setTimeout(function(){playSound("request");},3000);
	   	   this.soundTimer2 = setTimeout(function(){playSound("request");},6000);
	   }
        
       this.countDown();
};
$.extend($.chatRequest, {    
    DEFAULTS: { timeout:300000, to:'',context:'',   sellername:'',   forcedRequest:false }
});

$.chatRequest.prototype={
   pop:function(){
      var self = this;
      this.win = new Boxy(this.mycnt, { title: 'Contacting ... ' + this.options.sellername,beforeUnload:function(){  
	        for(var i = 0; i < chat.requests.length; i++){
	           if(chat.requests[i].id == self.id)chat.requests.splice(i,1);
	        }
	        return true;
	   }});
 
	  var wc = this.win.getContent();
      wc.find("a.accept").click(function(e){self.approve();    return false; });  
      wc.find("a.reject").click(function(e){self.reject();    return false; });
   },
   formatName:function(){
      if(this.plan)
	     return  this.options.from.Name + " ("+ this.options.context.ID + ")" ;
      else
	     return  this.options.from.Name + "("+ this.options.from.Id+ ")" ;
	},
	
	formatPlan:function()	{
	var pret="",plan = this.options.context;
	if(plan){
	    if(plan.ContractTerm && plan.ContractTerm>0)
            pret+=plan.ContractTerm +" MONTHS"+",";

        if (plan.phones.length>0) {   
           var phone=plan.phones[0]; 
            if(phone.ProductName!='undefined')   {
                if(phone.ProductName != "")
                pret+=phone.ProductName+",";
            } 
        }  
        if(plan.CashOffered!='undefined')
        if(plan.CashOffered > 0)
        pret+= plan.CashOffered+" CASH";
	}
	return pret;
	 
	}, 
	rendermypanelbymischat:function(){
	    var self = this;
        var hl = $('<div class="msdatachatdiv">');
        var lnk = $('<a href="javascript:void(0);" class="dchatlink" />');
        lnk.click(function(){
           self.pop();
        });
        
        var name = $('<div class="namedatachatdiv" />').html(this.formatName());
        var detail =$('<div class="detaildatachatdiv" />').html(this.formatPlan());
        lnk.append(name).append(detail);
        hl.append( $('<div style="float:left;" />').append(lnk)).append('<span class="cd">'+this.cur+'</span>');
        return hl;
     }, 
    createchatpanel:function(){
       this.panel = this.rendermypanelbymischat();
       if($(this.mini).find(".opportunity").length == 0){
            var r = $('<div class="livedivdata opportunity" style="width:930px;" />');
            var h = $('<div class="headchatdiv" />').html("CHAT OPPORTUNITIES");
            $(this.mini).append(r.append(h));
       }
       $(this.mini).find(".opportunity").append(this.panel);
         var cnt = $(".livebar .opportunity a").length;
         if(cnt >0){
           $('.live-status .opps').html(cnt + " New Opportunit"+ (cnt >1? "ies":"y")).show().css({color: '#ff0000'});
         }else{
           $('.live-status .opps').hide();
         }
	},
	
	countDown:function(){
	  var self = this;
	  var strSecond  = leftFill((this.cur -Math.floor(this.cur/60) *60),2);
      
      if(self.panel)
         self.panel.find(".cd").html( Math.floor(this.cur/60) + ":" + strSecond); 
	
	  if (this.win){
	    this.win.getContent().find(".countdown span").html( Math.floor(this.cur/60) + ":" + strSecond);     
	  }
      this.cur--;
     
      if(this.cur <0 ){
        this.cur = 0;
        this.stopCount();
      } else
        this.timer=setTimeout(function(){self.countDown();},1000);
    },
    stopCount:function(){
      if(this.timer > 0)clearTimeout(this.timer);
      if(this.soundTimer > 0)clearTimeout(this.soundTimer);
      if(this.soundTimer2 > 0)clearTimeout(this.soundTimer2);
      stopSound("request");
     
    },
    
    stop:function(){
       this.stopCount();
    },
    
    close:function(){this.stop();if(this.win)this.win.unload();},
    show:function(){
    //this.win.show();this.win.toFront();
    },
    
    approve:function(){
       this.stop();
    
       var params = {action:"approve",context:this.options.context.Id,type:this.options.type,from:chat.account.Id,to:this.options.from.Id};
       if(this.options.context == "support" ){
           params.context= this.options.context;
       }else{ 
           params.context = this.options.context.ID;
       }
       
       if(this.channel != null)
        params.channel=this.channel;
       var self = this;
       if(chat.account.Id < 0&& this.options.context !="support"){ // ping visitor
           var register = new $.register({context:self.options.context,plan:this.options.context,inline:false,registered:function(u){
                   chat.account = u;
                   params.from = chat.account.Id;
                   $.post("/lt.ashx",params, function(res) { self.onSent(res); },  'json');
             }});  
       } else {
           if(this.options.context == "support" ){
              this.win.setContent('<div style="text-align:center;padding:10px;" ><h3>Loading Live Support...</h3></div>'); 
           }else 
              this.win.setContent('<div style="text-align:center;padding:10px;" ><h3>Loading Live Transfer...</h3></div>');
              
           $.post("/lt.ashx",params, function(res) { self.onSent(res); },  'json');
       }
    },
	
	waitSellerPay:function(from,planid){
       var content = ' <div style="text-align:center;padding:5px;">';
       content +='<h3>Seller is making payment:<br />Approximate wait time:</h3> <div class="countdown" id="'+this.id+'requestCountDown">05:00</div></div>';

       this.win.getContent().update(content);
       $.title ( "Seller is making payment!");
       this.countDown();
    },
	
	reject:function() {
	    this.stop();
	    var now = new Date();
	    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
	    var rejecteds  = getCookie("rejected"); 
	    if(!rejecteds) 
	        rejecteds = this.plan.ID;  
	    else 
	        rejecteds += "," + this.plan.ID;
        setCookie("rejected",rejecteds , now);
        var params = [];
        params.push("party="+this.id);
        params.push("type="+this.type);
        params.push("name=reject");
        // Raman
        //params.push("cb=chat.request("+this.id+").onSent");
        if(this.plan)
            params.push("context=" + this.plan.ID);
        else
            params.push("context=");
        //chat.call(params);
        chat.call(params,"if(chat.request(" + this.id + ")!=null) chat.request("+this.id+").onSent");
        
        this.close();
	},
		
	onSellerNotAvaliable:function(){
	   this.stopCount(); 
	   var empty = "Enter date and time";
	   var content = '<form><div style="text-align:center;padding:5px;">';
	   content +='<p>Seller isn\'t avaliable right now, you can 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" name="message1"></textarea></li>';
	   content += '<li><label>>>I will be available at:</label> <input class="appinput" type="text" value="'+empty+'" /></li>';
	   content += '<li><b style="color:red" class="appdate" >Type a date above. eg "Tomorrow at 5pm" or "Next Sunday at 11am</b>. </li>';
	   content += '<li><a class="appconfirm" href="javascript:void(0);" ><img src="/images/send.png" alt="" /></a> ';
	   content += '<input type="hidden" name="message" class="appmessage" />';
	   content += '<input type="hidden" name="to" value="'+this.to+'" />';
	   content += '<input type="hidden" name="pid" value="'+this.context+'" />';
	   content += '</li></ul></div></form>';
      
	   this.win.setContent( content);
	   var self = this;
	   var input = this.win.getContent().find(".appinput");
	   input.keyup(function(e){
	        var date_string = $(r.app_date);
	       // var input = Event.element(e);
            date_string.removeClassName();
            if (input.value.length > 0) {
               date = Date.parse(input.value);
            if (date !== null) {
                input.removeClassName();
                date_string.addClassName("accept");
                date_string.innerHTML = date.toString('dddd MMMM d') + 'th at '+ date.toString('hhtt') +'(GMT'+date.getUTCOffset().substring(0,3)+')';
                $(r.app_msg).value = "Your party will be back at: " + date_string.innerHTML;
            } else {
            input.addClassName("validate_error");
            date_string.addClassName("error");
            date_string.innerHTML ="Wrong format.";
            $(r.app_msg).value = "";
        }
    } else {
        date_string.innerHTML = 'Type a date above. eg "Tomorrow at 5pm" or "Next Sunday at 11am';
        date_string.addClassName("empty");
    }
	  }).focus(function(e){jQuery(this).val('');}).blur(function(e){ $(this).val( empty);});
	  
	  $(this.app_confirm).click(function(e){
	     var input = Event.element(e);
	     var channel = input.id.split('_')[0];
	     var r = chat.requester(channel);
	     if($(r.app_msg).value ==""){
	        alert("Please input your date and time");
	        return;
	     }
	     $.post('/service/message.ashx?app=1',$(r.app_form).serialize(),function(transport, rs){
                if(rs.success) alert('Your message has sent');
                else alert(rs.message);
            },'json');
	    });
	},
	
	onSent:function(res){
	     if(this.panel)
	        this.panel.remove();
	    
	     var cnt = $(".livebar .opportunity a").length;
         if(cnt >0){
           $('.live-status .opps').html(cnt + " New Opportunit"+ (cnt >1? "ies":"y")).show().css({color: '#ff0000'});
         }else{
           $('.live-status .opps').hide();
         }
	    chat.closeRequest(this.id);
	}   
}

})(jQuery);	
