(function($) { 
 function chatChannel(options) {
    this.options = jQuery.extend({}, chatChannel.DEFAULTS, options || {});  
	this.win = false;
    this.channel = options.token;
    this.members = options.members;
    this.plan = options.context.plan;
    this.carrier = options.context.carrier;
    this.track = options.context.track;
    this.seller = {};
    this.buyer = {};
    this.plans = [];
	this.messageCounter = 0;
	this.lastMessage    = "";
	this.timer          = 0;
	this.swapper        = false;
	this.initiated      = false;
	this.ttimer         = 0;
	this.messages       = [];
	this.popwin         = false;
	this.selector       = false;
	this.offlineDialog  = false;		
    this.creatLayout();
    this.updateSupport();
    
    var self = this; 
    $(self.members).each(function(i){
        if(self.members[i].Id == self.track.SellerId)
           self.seller = self.members[i];
        if(self.members[i].Id == self.track.BuyerId)
           self.buyer = self.members[i];
    });
    this.editor = new $.chatEditor(this.win.getContent().find("textarea"),{channel: this.channel,  button: this.win.getContent().find("input.send"), typeSend: 0 });
};

window.chatChannel = chatChannel;
jQuery.extend(chatChannel, {    
    DEFAULTS: {ispopout:false }
});

chatChannel.prototype= {
    status:function(s){
       if(s){
          this.win.getContent().find("div.status").html(s);
       }
    },	
	creatLayout:function(){
	    var popstr = '';
		if(this.options.ispopout) 
		   popstr= '<a href="javascript:void(0);" class="popin"><img src="/live/images/popin.gif" alt="pop in"></img></a>';
		else 
		  popstr = '<a href="javascript:void(0);" class="popout"><img src="/live/images/popout.gif" alt="pop out"></img></a>';
			
		var commandbar = '<ul class="statusbar lt_statusbar">';
		    commandbar += '<li class="mute"><img src="/im/images/mute.gif" alt="" onclick="parent.chat.mute(this);" /></li>';
		    commandbar += '<li class="pop">'+popstr+'</li>';
		    commandbar += '<li><span class="support"><a href="javascript:void(0);"><img src="/images/spacer.gif" alt="" /></a></span></li>';
		    commandbar += '<li class="changeplan" ></li>';
		    commandbar += '<li class="status"><div class="status"></div></li>'
		var content = '<div class="message_main">';
            content +='<div class="message_plan"><div class="plan">No plan in processing with your party.</div>';
            content +='<div class="names member"></div></div><div  class="phone right"></div>';
            content += '<div class="channel">';
            content += '<div class="messages">';
            content += '<div class="messages_content"></div>';
            content += commandbar;
            content+= ' </div><div class="send"><textarea class="editor" style="z-index:10003" ></textarea></div></div></div>';
            content += '<div  class="tracker"><h4>Transfer Tracker</h4>';
            content += ' <ul  class="steps"></ul><br class="clear"/></div>';
	   var self = this;
       this.win = new Boxy(content, { title: 'CellSwapper.com Live Transfer',beforeUnload:function(){  	       
	          if(self.swapper.confirmToClose()){
	              self.swapper.confirmClose();
	          } 

	          if( self.selector){ 
	              self.selector.win.close();
	              self.selector = false;
	          }
	          
	          self.initiated=false;
	          self.left();
	       
	       if(typeof($.wizard)!='undefined'){
	             $.wizard.findBuyer();
	       }
	       return true;
	   }});
	   
	},
	
	updateSupport:function(){
		var s= this.win.getContent().find(".support");
		s.support();
		var self = this;
		if(s.hasClass("online")){
		   s.find("a").unbind("click").click(function(){
		      self.call();
		   });
		}else{
		   s.find("a").unbind("click");
		}
	},
	
	updateSelect:function(){
	   var w = this.win.getContent().find(".changeplan");
	   var self = this;
	   if(this.plans.length > 1){
		  w.html('<input style="font-size:14px;padding:2px;" type="button" value="Change plan"/>');
	      w.find("input").click(function(){self.showPlans()});
	   }
	    else
	      w.html('');
	},
	
	showPlans:function(){
	   if(!this.selector && this.plans){
	      var self = this;
	      var ps = {plans:this.plans,callback:function(planid){
	         self.changePlan(planid);
	         self.selector = false;
	      },close:function(){self.selector = false;}};
	      this.selector  = new $.planSelector(ps); 
	   }
	},

	changePlan:function(planID){
	   if(planID == this.plan.ID) return;
	   var self = this;
	   for(i = 0; i< this.plans.length; i++){
	      if(this.plans[i].ID == planID){
	         this.plan = this.plans[i];
	        // seller changed too?
	        if( this.track.SellerId != this.plan.VendorID){
	           this.track.BuyerId = this.track.SellerId;
	           this.track.SellerId = this.plan.VendorID;
	           this._init(this.track,this.plan);
	           this.showMember();
	        }
	        
	        // sync
           var ticket = {channel:this.channel,action:'changeplan',planid:planID,from:chat.account.Id}
           ticket.to = ((ticket.from == this.seller.Id)?this.buyer.Id:this.seller.Id); 
           $.postJSON("/lt.ashx",ticket,function(res) {});
	       self.showPlan();
            self.status('<img src="/im/images/load2.gif" alt="" />changing plan...');
	        if(self.selector)self.selector.win.unload();
	      }
	   }
	},
	
	xplan:function(by,members,tran,plan){
       chat.onNotice(this.channel,"Plan changed to " + plan.ProductName + " by " + this.member(by).Name);
       
       this.win.setStatusBar('&nbsp;');
	   this.plan = plan;
	   this.track = tran;
	   if(tran!= null){this._init(tran,plan);}
	   
       this.showPlan();
       this.swapper.initSteps();
       this.initiated = true;
       this.showMember();
	   this.updateSelect();
	   
	},
	// two way swapping.
	rplan:function(tran,plan){
       chat.onNotice(this.channel,"Start two way swapping: " + plan.ProductName );
       this.status('&nbsp;');
	   this.plan = plan;
	   this.track = tran;
	   if(tran!= null){this._init(tran,plan);}
	   
       this.showPlan();
       this.swapper.initSteps();
       this.initiated = true;
       this.showMember();
	   this.updateSelect();
	},
	
	call:function(){
	   var ticket = {channel:this.channel,action:'ping',from:chat.account.Id};
        $.postJSON("/lt.ashx",ticket,function(res) {
          //
        });
	},
	
	serialize:function(){
	   this.win.unload();
	   return this;
	},
	
	changeStatus:function(s){
	   if(this.editor) 
	      this.editor.enable();
	   if(this.to!=null) {
	      if(s == 1){
		     this.setTitle('<img src="/im/images/available_white1.gif" alt="" />'+this.to.Name);
           }else if(s == 2){
		     this.setTitle('<img src="/im/images/idle_white1.gif" alt="" />'+this.to.Name);
           } else if(s == 3){
	            this.setTitle('<img src="/im/images/busy_white1.gif" alt="" />'+this.to.Name);
	       }else if(s == 4){
	           this.setTitle('<img src="/im/images/idle_white1.gif" alt="" />'+this.to.Name);
	       }else if(s== 99){
	           this.setTitle('<img src="/im/images/offline_white1.gif" alt="" />'+this.to.Name);
	           this.disable();
	       }
	   }
	},
	
	disable:function(){
	   if(this.editor)this.editor.disable();
	},
	
	setupTransfer:function(){//1,seller,2,buyer,3,free
	   var plan = this.plan;
	   var track = this.track;
	   if(track!= null){this._init(track,plan);}
	   
       this.showPlan();
       if(typeof this.swapper != 'undefined' && this.swapper)
          this.swapper.initSteps.apply(this.swapper,[]);
       this.initiated = true;
       this.showMember();
	   this.updateSelect();
	   
	   
	   if(this.track){
	        if(this.track.BuyerId == chat.account.Id){
	            this.win.setTitle('CellSwapper.com Live Transfer   ... chatting with ' + this.seller.Name);
	        }  else    {
	            this.win.setTitle('CellSwapper.com Live Transfer   ... chatting with ' + this.buyer.Name);
	        }
	   }
	},
	
	_init:function(tran,plan){
	   var e = this.win.getContent().find(".steps");
	   if(tran.SellerId == chat.account.Id)
	      this.swapper= new Seller({e:e,o:this,seller:this.seller,buyer:this.buyer,track:tran,plan:plan});
	   else if(tran.BuyerId == chat.account.Id) 
	      this.swapper = new Buyer({e:e,o:this,buyer:this.buyer,seller:this.seller,track:tran,plan:plan});
	   else {
	      this.swapper = new Admin({e:e,o:this,buyer:this.buyer,seller:this.seller,track:tran,plan:plan});
	   }
	},
	
	add: function(message) {
	    this.messages.push(message);
		if (this.messageCounter >= 500) {
			for (var i = 0 ; i < 10 ; i++) {
				$(this.divMsgContent).removeChild($(this.divMsgContent).firstChild);
			}
			this.messageCounter -= 10;
		}
		if(message!=null)
		    this.lastMessage = message;  
		if(this.timer>0)   window.clearTimeout(this.timer);	
		
		this.add2(message);
	},

	member: function(Id) {
		for (i = 0; i < this.members.length; i++) {
			if (this.members[i].Id == Id) {
				return this.members[i];
			}
	    }
		return undefined;
	},
	
	remove:function(Id){
	   for (i = 0; i < this.members.length; i++) {
			if (this.members[i].Id == Id) {
			var r  = this.members[i]
				this.members.splice(i,1);
				return r ;
			}
	    }
	    return false;
	},
	
	indexOf:function(Id){
	   	for (i = 0; i < this.members.length; i++) {
			if (this.members[i].Id == Id) {
				return i;
			}
	    }
		return -1;
	},
	
	formatMember:function(member){
	  var r = member.Name + "(";
	  if(member.Role == "admin"){
	       r+="Support";
	  }else if(this.track){
	      if(this.track.SellerId == member.Id)
	         r+="Seller ";
	      else r+="Buyer "
	  }else if(member.Role == "seller") r+="Seller";
	  else r+= "Buyer";
	  
	  if(member.Role != "admin")
	      r+=  member.Id +")";
	  else r+=")";
	  return r;
	},
	
	showMember:function(){
	   var e = this.win.getContent().find(".member").html('');
	   var self = this;
	   $(this.members).each(function(i){
	      var m = $(this).get(0);
	      if(typeof m.Plans != 'undefined'){
	         $(m.Plans).each(function(){
	            self.plans.push($(this).get(0));
	         });
	      }
	      e.append($("<span />").html('<img src="/images/online.png" alt=""/>' + self.formatMember(m)));
	   });
	},
	
	onJoin:function(member){
	     if( this.indexOf(member.Id)<0)
	        this.members.push(member);
	     chat.add(this.channel, '<span class="notice">Notice : '+this.formatMember(member)+' has joined.</span>');
	     this.showMember();
	},
	
	onLeft:function(uid){
	     var m = this.remove(uid);
	     if(!m) return;
	     chat.add(this.channel, '<span class="notice">Notice : '+this.formatMember(m)+' has left.</span>');	  
	        
	     this.showMember();
	     
	     if(this.track.Status == 2){
	        this.showOfflineDialog(uid);
	     }
	},
	
	showOfflineDialog:function(to){
	   var plan = this.plan;
	   var self = this;
	   var content = '<div class="offline" ><h4>You can post an offline message to your party</h4>';
	   content += '<ul class="connect"><li><label>Message</label>';
	   content += '<input type="hidden" class="pid" name="pid" value="'+plan.ID+'" />';
	   content += '<input type="hidden" class="to" name="to" value="'+to+'" />';
	   content += '<textarea rows="6" name="message" class="offlinemessage"></textarea></li>';
	   content += '<li class="right"><a href="javascript:void(0);" class="cancel"><img  src="/images/cancel.png" alt="" /></a>';
	   content += '<a href="javascript:void(0);" class="submit"><img  src="/images/submit_l.png" alt="" /></a></li>';
       content += '</ul></div>';
	   var od = new Boxy(content, { title: 'Posting offline message'});
	   var odc = od.getContent();
       odc.find(".submit").click(function(e){
            var msg =  odc.find("textarea").val();
	        if(msg == ""){  
	           alert("Please input your message.");
	           return false;
	        }
	        $.postJSON('/service/message.ashx',{message:msg,pid:odc.find(".pid").val(),to:odc.find(".to").val(),from:chat.account.Id}, function(r){
                if(r.success){
                   alert('Your message has been sent');
                   odc.unload();
                }else{alert(r.message);}
            });
        });
        
       odc.find(".cancel").click(function(e){od.unload();});
	},
	
	left:function(){
	   if( this.members.length==2){
	    this.chatTranscript( $('#'+this.divMsgContent).html() );
	   }
	   chat.removeChannel(this.channel);
       $.postJSON("/live.ashx",{action: "left", Id: chat.account.Id, channel: this.channel });
	},
	
	chatTranscript: function(log)   {
        if(chat==null) return;
        if(log=='') return;
        
        var me_name=chat.name;
        var me_id = chat.account.Id;
        var myfriend_id = -1;
        var myfriend_name = '';
        var myfriend_name_formatted;
        
        for(var i=0;i<this.members.length;i++)        {
            if(this.members[i].Id != chat.account.Id)            {
                myfriend_id = this.members[i].Id;
                myfriend_name = this.members[i].Name;
                myfriend_name_formatted = myfriend_name + '(' + myfriend_id + ')';
                break;
            }
        }
        
        var formattedmsg = '';
        $("div.message").each(function(){
            var thismsg= jQuery(this).find("span.message").text();
            
            myname = jQuery(this).find("div.me").text();
            
            if(myname==null || myname==''){
                formattedmsg += myfriend_name_formatted+ " : "+ thismsg;
            }
            else
                formattedmsg += me_name + '(' + me_id + ')'+ " : "+ thismsg;
            
            formattedmsg += '<br />';
        });
        
        //mail this....
        $.postJSON('/service/message.ashx', {action:'sendchatlog', chatlog: formattedmsg},null);
    },
    
	showPlan: function() {
	  if(!this.plan) return;
	  var plan = this.plan;
	  var content = '<img class="planlogo" src="'+plan.ImageFileSmall+'" alt="" style="float:left"/>' ;
      content += '<span class="planname">'+plan.ProductName+'</span><br /><small class="sku">SKU: <a target="blank" href="'+$.getPlanUrl(plan.ID)+'" >'+plan.ID+'</a></small>';
       
      this.win.getContent().find("div.plan").html(content);
      if(plan.phones.length> 0){
         var phone = plan.phones[0];
         var p = '<img class="phonelogo" src="'+phone.ImageFileSmall +'" alt="" /><br class="clear" />';
         p+= phone.ProductName +'<br class="clear" />';
         this.win.getContent().find("div.phone").html(p);
      }
   },
   
   planSummary: function(){
    var ret='';
    ret+= '[' + this.plan.ProductName + ' ';
    if( this.plan.phones!=null)
        ret+= this.plan.phones.length>0 ? this.plan.phones.length + ' free phones ': '';
    ret+= this.plan.CashOffered>0 ? '$'+this.plan.CashOffered+' bonus' : ' ';
    ret+= ']' ;
    return ret;
   },
   
     onTyping:function(from){
         this.status(this.member(from).Name + " is typing... ");
         var self = this;
         this.ttimer = window.setTimeout(function(){self.status('&nbsp');},5000);
     },
     
     toggleTyping:function(){
        this.status("&nbsp;");
        clearTimeout(this.ttimer);
     },
   
	add2:function(){		
		var msgs = this.win.getContent().find(".messages_content");
        msgs.append($("<div />").html(this.lastMessage).addClass("message"));
        var last = msgs.find("div:last");
        if (last.offset())
            msgs.attr("scrollTop", last.offset().top);
        this.messageCounter++;
        $(".live .title-bar").addClass("title-on");
	},
	toString:function(){
	    var content = '<img src="'+this.plan.Image+'" alt="" /> ' ;
	    content += this.plan.ID + " ";
        for(i=0;i<this.members.length;i++){
	       content+= ', '+  this.formatMember(this.members[i]);
	    }
	    
	    content += ', pending to start. ';
	    return content;
	}
}

function onMessage(channel) {
    chat.current = channel;
	var msg = jQuery( 'channel_input_message_' + channel).value;
	if (msg && msg != '') {
		chat.message(msg);
	}
}
	
////////////////////// step //////
function Step(desc,status) {this.desc = desc;this.status = status; };	
///////////////////////Swapper /////
function Swapper(options) {
    if(options){
     this.options = jQuery.extend({}, Swapper.DEFAULTS, options || {});
     this.account = options.account;
     this.party = options.party;
     this.track = options.track;
     this.plan = options.plan;
     this.steps = [];
     this.e = options.e;
     this.o = options.o;
     this.testimonial = false;
     }  
};

$.extend(Swapper, {    
    DEFAULTS: { timeout:5000, to:'',context:'', backable:false,canreject:false,  sellername:'', confirmedToClose:false}
});

Swapper.prototype = {
	     confirmToClose:function(){return !this.confirmedToClose && this.track.Status !=0 && this.track.Status !=3 && this.track.Status!=4 &&this.track.Status!=5 &&this.track.Status!=8 && this.track.Status!=9;},
         formatName:function(user,prefix){
            if(prefix)
                return user.Name + "("+prefix+" " +user.Id+")";
            return user.Name + "(" +user.Id+")";
          },
          Active:function(step,content){
             var act = this.e.find(".stepactive");
             if(act.length > 0){act.remove();}
             var before = this.e.find(".step"+step);
             var cur = $("<li />").addClass("stepactive");
             cur.append("<b>STEP"+(step+1) +":</b><p>"+content + "</p>");
             cur.css("style","border:solid 1px #888;");
             if(before.length>0)
                before.before(cur);
              else
                this.e.append(cur);
          },
          updateTrack:function(track){
             this.track  = track;
             this.checkSteps();
             this.updateBottom(true);
          },
   
          updateBottom:function(r){
             var content = "<div>";
             if(r && this.e.parent().find("div:last-child").length >0 )this.e.parent().find("div:last-child").remove();             
             if( this.backable){
               content += '<input type="button" value="Back" class="back" />';         
             }
             
             if(this.canreject){
                 content += '<input type="button" value="Reject" class="reject" />';         
             }
             
             content += "</div>";
             
             this.e.append( content);
             var self = this;
             this.e.find("input.back").click(function(e){
                self.back();
              });
             this.e.find("input.reject").click(function(e){
                self.reject();
              });
          },
          
          stop:function(){
             var reason = $("#lstReason").val();
             if(reason == ""){
                alert("Please select the problem of transfer.");
                return false;
             }else
                 this.doCommand("stop",reason);
          },
          init:function(partyReady){
             var content ='Ready to proceed? When both parties have agreed on terms and would like to continue with the transfer, please click the CONFIRM button. If you are no longer interested in this transfer with this buyer click CANCEL.<br />';
                 content +='<input type="button" value="Confirm" class="confirm"/> <input type="button" value="Cancel" class="cancel" />';
             if(partyReady)
                 content += 'Your party has confirmed to process. <br />';
              
             this.Active(0,content);
             var self = this;
            this.e.find(".confirm").click(function(e){
                self.o.initiated=false;
                self.initConfirm();
         });
          
           this.e.find(".cancel").click(function(e){self.cancel(); });
        },
    
    initConfirm:function(){
        var ticket = {channel:this.o.channel,action:"init",from:chat.account.Id};
        var self = this;
        $.post("/lt.ashx",ticket,function(res) {
           if(res.status == 1){
              self.updateTrack(res.msg);
           }
        },'json');
    },
    
    waitInit:function(){
       var content = 'Please wait until the other party has also agreed to proceed.';
       this.Active(0,content);
    },
    
    onError:function(msg ){
       var content = 'Error! ' + msg;
       this.Active(0,content);
    },
    
    cancel:function(){
        var reject = '<select id="lstReason">';
          reject += '<option value="">Select</option>';
            for(i=0; i< this.track.Reasons.length; i++){
               reject += '<option value="'+ this.track.Reasons[i] + '">'+ this.track.Reasons[i]+'</option>';
            }
            reject += '</select><br /> ';
            
        var content ='Please select reason from this list and press the submit button.';
        content +=reject;
        Dialog.confirm(content, {width:275,okLabel: "Submit",id: this.o.channel+"_Cancel", 
                cancel:function(win) {
                }, 
                ok:function(win) { 
                    var reason = $("lstReason").options[$("lstReason").selectedIndex].value;
                     if(reason == "")
                     {
                        alert("Please select the problem of transfer.");
                        return false;
                     }
                
                   var c = chat.channel(win.getId().split('_')[0]);
                   c.swapper.confirmedToClose = true;
                   c.swapper.stop();
                   win.close();
                   c.win.close();
                   return true; 
               } 
           });
    },
    
    buyerRejected:function(){
       var content = this.track.BuyerFullName + ' (Buyer ) has rejected the transfer: ' + "<br />";
          content+= '  ' + this.track.BuyerRejectReason;
       this.Active(5,content); 
    },
    
    confirmClose:function(){
       var self = this;
       var content = "Do you wish to Proceed with this contract transfer later? OR Reject this transfer?";
        Boxy.ask(content, ['Do it later','Reject it'],function(c) {
              if(c == 'Reject it' ){    
                 self.reject();
                 return false;
              }else {  
                 self.confirmedToClose = true;
                 return true;
              } 
       });
       
    },
    
    reject:function(){
          var reject = '<h4>Please select a reason to continue:</h4><select class="lstReason" style="width:auto;">';
          reject += '<option value="">Select</option>';
            for(i=0; i< this.track.Reasons.length; i++){
               reject += '<option value="'+ this.track.Reasons[i] + '">'+ this.track.Reasons[i]+'</option>';
          }
            
          reject += '</select><br />';
          var self = this;
       Boxy.confirm(reject, function(c) {
             self.confirmedToClose = true;
             self.stop();
             return true;    
          });
          
        
    },
    
    sellerRejected:function(){
        var content = this.track.SellerFullName + ' (Seller ) has rejected the transfer: ' + "<br />";
          content+= '  '+this.track.TransferProblemSeller;
       this.Active(5,content); 
    },
    
    back:function(){
        var ticket = {channel:this.o.channel,action:"back",from:chat.account.Id};
        var self = this;
        $.post("/lt.ashx",ticket,function(res) {
           if(res.status == 1){
              self.updateTrack(res.msg);
           }
        },'json');
    },
    
    showTestimonial:function(){
       if(this.testimonial)this.testimonial.win.show();
       else this.testimonial = new Testimonial(this,{id:this.o.channel});
    },
    
    initSteps:function(){
       this.e.html('');
       this.steps.push(new Step("Buyer and seller confirm interest in initiating transfer.",0));
       this.steps.push(new Step("Buyer Calls "+this.o.carrier.name+" and confirms.",0));
       this.steps.push(new Step("Seller Calls "+this.o.carrier.name+" and Confirms.",0));
       
       if(this.track.PhoneName!=""){
           this.steps.push(new Step("Seller provides shipping information.",0));
           this.steps.push(new Step("Buyer confirms receipt of phone.",0));
       }
            
       for(i=0; i< this.steps.length;i++){
           var s = this.steps[i];
           if(s.status == 0){
              var lid = $("<li />").addClass("step"+i).addClass("disabled").html("STEP"+(i+1)+": "+  s.desc);
              lid.css({color :"#c0c0c0",fontSize:"11px"});
              this.e.append(lid);
           }else            
              this.e.append('<li class="step'+i+'">'+"STEP"+i+": "+ s.desc+'</li>');
      }
       
      this.checkSteps();
      this.updateBottom(false);
    }
 }
	
///////////////////////////////////
function Seller(options) {
   Swapper.call(this,options);
};

$.extend(Seller.prototype,Swapper.prototype);
$.extend(Seller.prototype, {
    checkSteps:function(){
       this.backable = true;
       this.canreject = true;
       if(this.track.Status == 0){ // not start
           this.init(false);
           this.backable = false;
           this.canreject = false;
           return;
       }else if (this.track.Status == 9 ){
          this.backable = false;
          this.canreject = false;
          this.init(false);
          return;
       }else if(this.track.Status == 1 ){
           this.init(true);
           this.canreject = false;
           return;
       }else if(this.track.Status == 11 ){
           this.waitInit();
           this.canreject = false;
           return;
       }else if(this.track.Status == 5){
           this.backable = false;
           this.canreject = false;
           this.buyerRejected();
           if(typeof(jQuery)!='undefined' && typeof(jQuery.wizard)!='undefined'){
              $.wizard.findBuyer();
           }
           return;
       }else if(!this.track.bPowerSeller){
          this.needPayment();
          return;
       }else if(this.track.Status == 3){
           this.backable = false;
           this.canreject = false;
           this.onComplete();
           return;
       }else if(this.track.Status == 8){
           this.backable = false;
           this.canreject = false;
           this.sellerRejected();
           if(typeof(jQuery)!='undefined' && typeof(jQuery.wizard)!='undefined'){
              $.wizard.findBuyer();
           }
           return;
       }else if(this.track.TransferSecretCode ==""){
           this.Call(); 
           return;
       }else if(!this.track.IsBuyerConfirmedCode){
           this.onsellercalled();return;
       }else if(this.track.IsBuyerConfirmedCode && !this.track.IsSellerConfirmedTransfer){
           this.onconfirmcode();return;
       }else if(this.track.IsSellerConfirmedTransfer){
           if(this.track.PhoneName == ""){
               this.backable = false;
               this.onComplete();
               this.canreject = false;
               return;
           }else if(this.track.ShipperName==""){
               this.shipPhone();
               return;
           }else{
             if(this.track.BuyerConfirmedPhoneReceived){this.canreject = false; this.backable = false; this.onComplete();}
              else
              this.onShipped();
           }
       }
    },
    
    needPayment:function(){
        var content = '<br /><a href="javascript:void(0);" class="pay">Click here to proceed with $24.95 Live Transfer payment.</a><br/>';
           content +=' (If for any reason the transfer with this buyer does not complete, Cellswapper will immediately scan for another buyer at no charge. There will never be any additional charge for this service.<br />';
        this.Active(0,content);
        var self = this;
        this.o.win.getContent().find("a.pay").click(function(e){ self.pay(); });
    },
    pay:function(){
        var self =this;
        var chk = new $.Checkout({planid:this.o.plan.ID,channel:this.o.channel,type:3,onPaid:function(){
               var ticket = {channel:self.o.channel,action:"pay",from:chat.account.Id};
               $.post("/lt.ashx",ticket,function(res) {
                    if(res.status == 1){
                       self.updateTrack(res.msg);
                    }
               },'json');
        }});
    },
    
    Call:function(){
       var content = 'Call '+ this.o.carrier.name + ' at '+ this.o.carrier.phone;
          content+= ' , request a transfer of service/liability with '+this.formatName(this.o.buyer)+' and provide their contact details:';
          content+= ' <br />Buyer Name: '+this.o.buyer.Name + "<br />";
          content+= ' Buyer Phone: '+this.o.options.context.buyerphone;
          content += '<p style="text-align:center;width:134px;height:50px;" >Secret code:<input type="textbox" class="transec" style="width:70px"></input><br /> <input type="button" value="Save" class="save" /></p>';
        this.Active(1,content);
        var self = this;
        this.e.find("input.save").click(function(){
           self.called();
        });
    },
    
    called:function(){
      var sec = this.e.find(".transec").val();
      var self = this;
      if(sec=="")alert("Please enter valid secret code which you provided to the cellular company.");
      else{        
         var ticket = {channel:self.o.channel,action:"oncalled",from:chat.account.Id,context:sec};
         $.post("/lt.ashx",ticket,function(res) {
                    if(res.status == 1){
                       self.updateTrack(res.msg);
                    }
          },'json');
      }
    },
    
    onsellercalled:function(){
       var content = 'Please wait for buyer to call '+this.o.carrier.name+' to proceed with transfer ';
        this.Active(2,content);
    },
    
    onconfirmcode:function(){   
        var content = 'Call '+ this.o.carrier.name + ' at '+ this.o.carrier.phone;
        content += ' , and confirm that the transfer has been completed successfully.';
        content += ' Please confirm by pressing <input type="button" value="OK" class="confirmcodeback" />';
       
       this.Active(2,content);
       var self = this;
       this.e.find("input.confirmcodeback").click(function(){
          self.confirmCodeBack();
       });
    },
    
    confirmCodeBack:function(){
       var msg = "You are about to confirm that you called back to carrier and confimed that plan was successfully transferred to buyer."; 
       var self = this;
       if(confirm(msg)){
         var ticket = {channel:self.o.channel,action:"confirmcodeback",from:chat.account.Id};
         $.post("/lt.ashx",ticket,function(res) {
                    if(res.status == 1){
                       self.updateTrack(res.msg);
                    }
          },'json');
       }
    },
    
    onsellerconfirmcode:function(){
       if(this.track.PhoneName == "")
          this.onComplete();
        else
          this.shipPhone();
    },
    
    shipPhone:function(){
      var content = "You are now required to send your " + this.track.PhoneName + ' phone and/or incentives.<br />';
      content +='Once you have shipped your phone and/or other incentives offered, please enter the shipping name and tracking number here:<br />';
      content += '<div style="text-align:center;" >';
      content += 'Shipper Name:<input type="textbox" class="name" style="width:120px"></input><br /> ';
      content += 'Tracking Number:<input type="textbox" class="number" style="width:120px"></input><br /> ';
      content += 'URL to track:<input type="textbox" class="url" style="width:120px"></input><br /> ';
      content += '<input type="button" style="width:130px;font-size:11px;" value="Send Tracking Information" class="ship" /></div>';
      this.Active(3,content);
      var self = this;
      this.e.find("input.ship").click(function(){
         self.shipit();
      });
    },
    
    shipit:function(){
        var name = e.find(".name").val();
        if(name==""){
           alert("Please provide shipper name");
           return;
        }
        var number = e.find(".number").val();
        if(number == ""){
           alert("Please provide tracking number");
           return;
        }
        var url = e.find(".url").val();
        
        var ticket = {channel:self.o.channel,action:"shipphone",from:chat.account.Id,shipname:name,shipnumber:number,shipurl:url};
        $.post("/lt.ashx",ticket,function(res) {
                    if(res.status == 1){
                       self.updateTrack(res.msg);
                    }
          },'json');
    },
    
    onShipped:function(){
        var content = 'Please wait for buyer to confirm receipt of phone. ';
        this.Active(4,content);
    },
    
    onComplete:function(){
      var content  = 'Congratulations! your plan has been successfully transferred to '+this.track.BuyerFullName +'. ';
      content += 'Please <a href="javascript:void(0);" class="posttest" >post a testimonial</a> to tell others about your experience with Cellswapper. Thank you for using Cellswapper';
      this.Active(5,content);
      this.showTestimonial();
      var self = this;
      this.o.win.getContent().find("a.posttest").click(function(e){
            self.showTestimonial();
       });
    }
});

/////////////////Buyer//////////////////
function Buyer(options) {
   Swapper.call(this,options);
};

$.extend(Buyer.prototype,Swapper.prototype);
$.extend(Buyer.prototype, { 
    checkSteps:function(){
       this.backable = true;
       this.canreject = true;
       if(this.track.Status == 0){ // not start
            this.backable = false;
            this.canreject = false;
            this.init(false);
           return;
       }else if (this.track.Status == 9){
            this.backable = false;
            this.canreject = false;
           this.init(false);
           return;
       }else if(this.track.Status == 11 ){
           this.init(true);
           this.canreject = false;
           return;
       }else if(this.track.Status == 1 ){
           this.waitInit();
           this.canreject = false;
           return;
       }else if(!this.track.bPowerSeller){
          this.needPayment();
          return;
       }else if(this.track.Status == 3){
           this.onComplete();this.canreject = false; this.backable = false;
           return;
       }else if(this.track.Status == 8){
           this.backable = false;this.canreject = false;
           this.sellerRejected();
           return;
       }else if(this.track.Status == 5){
           this.backable = false;this.canreject = false;
           this.buyerRejected();
           return;
       }else if(this.track.TransferSecretCode ==""){
           this.WaitSellerCall();
           return;
       }else if(!this.track.IsBuyerConfirmedCode){
           this.onsellercalled();
           return;
       }else if(this.track.IsBuyerConfirmedCode && !this.track.IsSellerConfirmedTransfer){
           this.onconfirmcode();
           return;
       }else if(this.track.IsSellerConfirmedTransfer){
           if(this.track.PhoneName == ""){
               this.onComplete(); this.backable = false;this.canreject = false;
               return;
           }else if(this.track.ShipperName==""){
              this.onsellerconfirmcode();
              return;
           }else {
              if(this.track.BuyerConfirmedPhoneReceived) {this.onComplete();this.canreject = false; this.backable = false;}
              else
              this.onShipped();
           }
       } 
    },
    
    needPayment:function(){
       var content ='The seller must now pay a fee to proceed, please wait for the seller to complete the payment.';
       this.Active(1,content);
    },
    
    WaitSellerCall:function(){
       var content = this.o.seller.Name + ' has not yet called ' + this.o.carrier.name+'. Please wait for '+this.o.seller.Name +' to call '+this.o.carrier.name+' to get the process started.';
       this.Active(1,content);
    },
    
    onsellercalled:function(){
       var content = ' Call ' + this.o.carrier.name + ' at '+ this.o.carrier.phone+' , request to take over the contract of '+this.o.seller.Name+' and provide the following information:<b>'+ this.track.TransferSecretCode+"</b>";
       content += '<br />After ' + this.o.carrier.name + ' has confirmed that this transfer has been completed, please let '+this.o.seller.Name+'(seller) know by pressing the button below. ';
       content += '<br /><input type="button" value="OK" class="confirm" /> ';
       this.Active(2,content);
       
       var self = this;
       this.e.find("input.confirm").click(function(){
          self.confirm();
       });
    },
    
    confirm:function(){
       var msg = "You are about to confirm that you have successfully taken over the plan."; 
       var self = this;
       if(confirm(msg)){
         var ticket = {channel:self.o.channel,action:"confirmcode",from:chat.account.Id};
         $.post("/lt.ashx",ticket,function(res) {
                    if(res.status == 1){
                       self.updateTrack(res.msg);
                    }
          },'json');
       }
    },
    
    onconfirmcode:function(){
         var content = this.o.seller.Name + ' has not yet called '+this.o.carrier.name+' to confirm transfer was successful.';
         this.Active(2,content);
    },
    
    onsellerconfirmcode:function(){
        if(this.track.PhoneName != "" ){
         //has phone? wait for the information
          var content = this.o.seller.Name + ' has not yet provided shipping information for the '+this.track.PhoneName+' and/or other incentives offered.';
          this.Active(3,content);
         }
        else
          this.onComplete();
       
    },
    
    onShipped:function(){
       var content = ' Tracking Information: ';
       content += '<br /> Shipper Name:<br /> ' + this.track.ShipperName;
       content += '<br /> Tracking Number:<br />  '+ this.track.TrackingNumber;
       content += '<br /> URL to track:<br />  ' + this.track.TrackingURL;

       content += '<p>Once you have received the 3 phone and/or other incentives, please confirm by pressing ';
       content += ' <input type="button" value="ok" class="onreceived" />  </p>';
       this.Active(5,content);
       
       var self = this;
       self.e.find("input.onreceived").click(function(){
          self.onReceived();
       });
    },
    
    onReceived:function(){
       var self = this;
        var ticket = {channel:self.o.channel,action:"received",from:chat.account.Id};
         $.postJSON("/lt.ashx",ticket,function(res) {
             if(res.status == 1){
                 self.updateTrack(res.msg);
         }});
        this.onComplete();
    },
    
    onComplete:function(){
      var content  = 'Congratulations! your has successfully taken over plan of '+this.track.SellerFullName+'. ';
      content += 'Please <a href="javascript:void(0);" class="posttest" >post a testimonial</a> to tell others about your experience with Cellswapper. Thank you for using Cellswapper';
      this.Active(6,content);
      this.showTestimonial();
      var self = this;
      this.o.win.getContent().find(".posttest").click(function(e){
            self.showTestimonial();
        });
    }
});

	/////////////////////////////////////
/////////////////Admin//////////////////

/////////////////Buyer//////////////////
function Admin(options) {
   Swapper.call(this,options);
};

$.extend(Admin.prototype,Swapper.prototype);
$.extend(Admin.prototype, {    
    checkSteps:function(){
       if(this.track.Status == 0){ // not start
           this.init(false);
           return;
       }else if (this.track.Status == 9){
           this.init(false);
           return;
       }else if(this.track.Status == 11 ){
           this.init(true);
           return;
       }else if(this.track.Status == 1 ){
           this.waitInit();
           return;
       }else if(!this.track.bPowerSeller){
          this.needPayment();
          return;
       }else if(this.track.Status == 3){
           this.onComplete();
           return;
       }else if(this.track.Status == 8){
           this.sellerRejected();
           return;
       }else if(this.track.Status == 5){
           this.buyerRejected();
           return;
       }else if(this.track.TransferSecretCode ==""){
           this.WaitSellerCall();
           return;
       }else if(!this.track.IsBuyerConfirmedCode){
           this.onsellercalled();
           return;
       }else if(this.track.IsBuyerConfirmedCode && !this.track.IsSellerConfirmedTransfer){
           this.onconfirmcode();
           return;
       }else if(this.track.IsSellerConfirmedTransfer){
           if(this.track.PhoneName == ""){
               this.onComplete();
               return;
           }else if(this.track.ShipperName==""){
              this.onsellerconfirmcode();
              return;
           }else
           {
              if(this.track.BuyerConfirmedPhoneReceived) this.onComplete();
              else
              this.onShipped();
           }
       } 
    },
    confirmToClose:function(){return false;},
    init:function(){
         var content ='Transfer not started yet <br />';
         this.Active(0,content);
    },
    
     needPayment:function(){
       var content ='The seller must now pay a fee to proceed, please wait for the seller to complete the payment.';
       this.Active(1,content);
    },
    
    WaitSellerCall:function(){
       var content = this.o.seller.Name + ' has not yet called '+this.o.carrier.name+'.';
       this.Active(1,content);
    },
    
    onsellercalled:function(){
       var content = this.o.seller.Name + ' provide the following secret code:<b>'+ this.track.TransferSecretCode+"</b>";
       this.Active(2,content);
    },
    
    onconfirmcode:function(){
         var content = 'Buyer confirmed the transfer was successful.';
         this.Active(2,content);
    },
    
    onsellerconfirmcode:function(){
        if(this.track.PhoneName != "" ){
          var content = this.o.seller.Name + ' has not yet provided shipping information for the '+this.track.PhoneName+' and/or other incentives offered.';
          this.Active(3,content);
         }
        else
          this.onComplete();
       
    },
    
    onShipped:function(){
       var content = ' Tracking Information: ';
       content += '<br /> Shipper Name:<br /> ' + this.track.ShipperName;
       content += '<br /> Tracking Number:<br />  '+ this.track.TrackingNumber;
       content += '<br /> URL to track:<br />  ' + this.track.TrackingURL;
       this.Active(5,content);
    },
    
    onReceived:function(){
        this.doCommand("received","");
        this.onComplete();
    },
    
    onComplete:function(){
      var content  = 'This transfer completed successfully.';
      this.Active(6,content);
    }
});


/// 
function Testimonial(swapper,options) {
    this.options = $.extend({}, Testimonial.DEFAULTS, options || {});  
	this.win = false;
    this.id = options.id;
    this.swapper = swapper;
	this.win = false;
        
		var content = '<form enctype="multipart/form-data" method="post" type="" action="/service/Testimonial.ashx#" >';
		    content += '<ul class="connect"><li><label>Your Name:</label><input name="name" type="text" class="name" value="'+chat.account.Name+'"/></li>';
            content += '<li><label>Your Location:</label><input name="location" type="text" class="location"  /></li>';
            content += '<li><label>Your Picture:</label><input type="file" name="photo" class="photo" /></li>';
            content += '<li><label>Testimonial:</label><textarea name="text" rows="6" class="text" ></textarea></li>';
            content += '<li><label style="width:200px;">Tell your friends:</label><textarea name="emails" rows="2" style="height:30px" class="emails"></textarea><br /><small>split emails with a comma</small></li>';
            content += '<li class="right"><a href="javascript:void(0);" class="cancel"><img src="/images/cancel.png" alt="" /></a>';
            content += '<a href="javascript:void(0);" class="submit" ><img  src="/images/submit_l.png" alt="" /></a></li>';
            content += '</ul>';
            content += '<input type="hidden" value="parent.chat.channel('+this.id+').swapper.testimonial.onPosted({0});" name="callback" /></form>';
	        content += '<iframe style="border: 0pt none;padding: 0pt; height: 0pt; width: 0pt; position: absolute;" src="/service/Testimonial.ashx#" />'
 
	   this.win = new Boxy(content, { title: 'CellSwapper.com Submit Testimonials',beforeUnload:function(){  	       
	   }});
	    
	   odc = this.win.getContent();
	   var field1 = new LiveValidation( odc.find(".name").get(0), {validMessage:""} );
       field1.add( Validate.Presence,{failureMessage:''} );
       var field2 = new LiveValidation( odc.find(".photo").get(0), {validMessage:'' } );
       field2.add( Validate.Presence, {failureMessage:""} );
       var field3 = new LiveValidation( odc.find(".text").get(0), {validMessage:""}  );
       field3.add( Validate.Presence ,{ failureMessage:''});  
       var self = this;
       odc.find('.submit').click(function(e){
            self.post();
        });
        
        odc.find('.cancel').click(function(e){
            self.win.unload();
            self.swapper.testimonial = false;
        });
};

window.Testimonial = Testimonial;
$.extend(Testimonial, {    
    DEFAULTS: { }
});

Testimonial.prototype= {
	post:function(){
	     odc = this.win.getContent();
	    if(odc.find(".name").val()==""){alert("Please input your name.");return;}
	    if( odc.find(".photo").val() == ""){alert("Please select a picture."); return;}
	    if(odc.find(".text").val() == ""){alert("Please say something."); return;}
	    odc.find("form").submit();
	    this.win.getContent().append('<br /><img class="loading" src="/im/images/load2.gif" alt="" />posting testimonial...');
	},
	
	onPosted:function(response){
	   if(response.Success){
	      this.win.unload();
	   }else{
	      alert(response.Message);
	   }
	   
	   this.win.getContent().find('.loading').hide();
	}
}

})(jQuery);