
$(document).ready(function() {

	ticketlist.intervalid = 0;
	ticketlist.intervalRate = 0;

	ticketlist.PopulateTicketFilters = function(name,custom,render) {

		var customerid = 0;
		ticketlist.grid.baseParams.start = 0;
		if (typeof(render)==="undefined") render=false;

		//check to see if we are supposed to be filtering by customerid
		if (typeof(ticketlist.searchcustomerid) != "undefined") {
			ticketlist.grid.baseParams.customerid = ticketlist.searchcustomerid;
			customerid = ticketlist.searchcustomerid;
		} else {
			ticketlist.grid.baseParams.customerid = 0;
		}

	
		History.pushState({}, "", "index.php?fuse=support&view=ViewTickets");
		if (ticketlist.searchfilter==="") {
			ticketlist.grid.baseParams.filter = "open";
	    } else if (ticketlist.searchquery ==="") {
	    	//lets clear out search query so refreshes will not search it
			$('#ticketsearchinput').val('');

			ticketlist.grid.baseParams.filter = ticketlist.searchfilter;
			if (customerid == 0) {
				History.pushState({}, "", "index.php?fuse=support&view=ViewTickets&searchfilter="+ticketlist.searchfilter);
			} else {
				History.pushState({}, "", "index.php?fuse=support&view=ViewTickets&filter="+ticketlist.searchfilter+"&customerid="+customerid);
			}
	    } else if (ticketlist.searchquery!="") {
			ticketlist.grid.baseParams.query = ticketlist.searchquery;
			ticketlist.grid.baseParams.filter = ticketlist.searchfilter;
			ticketlist.grid.baseParams.searchtype = ticketlist.searchtype;
			History.pushState({}, "", "index.php?fuse=support&view=ViewTickets&filter="+ticketlist.searchfilter+"&query="+ticketlist.searchquery+"&searchtype="+ticketlist.searchtype);
	    }

		if (typeof(custom) === "undefined") custom = false;
		if(custom) {
            label = "<a href='javascript:ticketlist.loadCustomFilterWindow(\""+ticketlist.searchfilter+"\");' id='ticketlist-editcustom-filter' qtip='Click to edit custom filter'>"+lang('Custom Filter')+': '+name+"</a>";
        } else {
            label = name;
        }
        document.getElementById('ticketlisttablelabel').innerHTML = lang("Viewing") + "&nbsp;" + label;

    	if (render) ticketlist.grid.render();

	}


	ticketlist.SearchTroubleTickets = function() {
		var filtertext,searchtype,filter;

	    filtertext = trim($('#ticketsearchinput').val());
	    searchtype = Ext.getCmp('searchtype').getValue();

	    if (filtertext == ""){
	        filter = "open";
	    } else if(document.getElementById("includeclosed").checked){
	        filter = "searchclosed";
	    }else{
	        filter = "searchopen";
	    }

	    if (filtertext == ""){
	        document.getElementById('ticketlisttablelabel').innerHTML = lang("Viewing All Open Tickets");
			History.pushState({}, "", "index.php?fuse=support&view=ViewTickets&searchfilter=open");
	    } else {
	        document.getElementById('ticketlisttablelabel').innerHTML = lang("Viewing") + " " + lang("Search Results For ") + "<b>"+$('#ticketsearchinput').val()+"</b>";
			History.pushState({}, "", "index.php?fuse=support&view=ViewTickets&filter="+filter+"&query="+filtertext+"&searchtype="+searchtype);
	    }

		ticketlist.grid.baseParams.customerid = 0;
	    ticketlist.grid.reload({params:{start:0,filter: filter, query:filtertext, searchtype: searchtype}});
	}


	ticketlist.loadCustomFilterWindow = function(id)
	{

    	$.ajax({
          url: "index.php?fuse=support&action=getTicketFilters",
	      dataType: 'json',
	      data: {customId: id},
	      success: function(json) {

	      	for ( var i in json.options )
            {
            	if (json.options[i].type == "customfilter" && json.options[i].id == id) {
            		$('#filtername').attr('value',json.options[i].name);
            		if (json.options[i].private!=0) $("#filterprivate").attr("checked", true);
            		else $("#filterprivate").attr("checked", false);
				}
            }
        	$('#idfilter').val(id);

            ticketlist.window = new RichHTML.window({
		    	height: '90',
		    	el: 'ticketlist-custom-filter',
		    	actionUrl: 'index.php?fuse=support&action=SaveTicketFilter',
		    	deleteUrl: 'index.php?fuse=support&action=DeleteTicketFilter',
		    	showSubmit: true,
		    	showDelete: true,
		    	onSubmit: function(data,params) {
		    		var name;
		    		jQuery.each(params, function(i, field){
		    			if (field.name == "filtername") name = field.value;
			        });
		    		ticketlist.PopulateTicketFilters(name,true, false);
		    		ce.msg(lang('Your filter has been saved'));
		    		callTicketSummaries();
		    	},
		    	onDelete: function(data) {
		    		ticketlist.searchfilter = "open";
		    		ticketlist.PopulateTicketFilters(lang("All Open Tickets"),false, true);
		    		callTicketSummaries();
		    	},
		    	title: lang("Ticket Filter")
		    });
		    ticketlist.window.show();
	      }
      });

	}

	ticketlist.renderExpander = function(value,record,el)
	{

		$.ajax({
          url: "index.php?action=getLastXTicketMessages&fuse=support",
	      dataType: 'json',
	      async: false,
	      data: {ticketid: record.id},
	      success: function(json) {

	         expanderBody = "";
             for ( var i in json.logs )
             {

	                entry = json.logs[i];
	                if (typeof(entry) != "object") continue;

	                userText = entry.name;
	                privateText = "";

	                if (entry.skip) {
	                    expanderBody += "<center><span style='color:#888;font-weight:bold;'>"+entry.msg+"</span></center>";
	                } else {
	                    if (entry.isprivate == "1") privateText = " <span style='float:right;color:red;font-weight:bold;'>private</span>";
	                    if (entry.isadmin) userText = "<span style='color:green;'>"+entry.name+"</span>";
	                    expanderBody += "<div class='ext-expanderframe'>";
	                    expanderBody += "<div class='ext-expanderframe-details'>";
	                    expanderBody += "<b>"+lang("By")+":</b> "+userText+"&nbsp;&nbsp;<b>"+lang("Date")+":</b> "+entry.date+privateText;
	                    expanderBody += "<div style='padding-top:8px;'>"+entry.msg+"</div>";
	                    expanderBody += "</div>";
	                    expanderBody += "</div>";
	                }
	          }

	      }
	    });
	    return expanderBody;
	}

    // renders Subject based on based record
   	ticketlist.renderSubject = function(value, record, el) {
   		var colorstyle = "",priorityclass="";

   		//we want to check if we just came from a query
   		//so we can pass it to ticket to highlight the word
		if (record.query != "") {
            filter = "&expand=1&query=" + record.query;
        } else {
            filter="";
        }

        if ( record.subject == '' ) {
            record.subject = 'No Subject';
        }


        var attachment = "", recordId=0, colorstyle = "", title="";
        if (record.hasAttachment) {
             attachment = "<img src='../images/190.png' alt='attachment' style='padding-left:4px;padding-right:3px;position: relative;top: 1px;' />";
        }

        recordId = companyfied? record.hashedid : record.id;

        if(record.isguest){
        	customerName = "<span style='color:gray;'>("+trim(record.submittedby)+")</span>";
        } else {
	        if(record.usergroupcolor!=""){
				customerName = String.format("<span class='customergroupstyle'><a href='index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID="+record.userid+"' style='background:{1};text-shadow: none;'>{0}</a></span>",record.submittedby,record.usergroupcolor);
	        }else{
		        customerName = String.format("<a href='index.php?fuse=clients&view=Admin_Profile_Contact&frmClientID={1}' style='text-shadow: none;color:#BD5A35'>{0}</a>",record.submittedby,record.userid);
	        }
        }

        if (filter == "") {
			subject = "<a href='index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID="+record.id+"' "+colorstyle+">"+record.subject+"</a>";
		} else {
			subject = "<a href='index.php?fuse=support&view=Admin_ViewTicketMessage&ticketID="+record.id+filter+"' "+colorstyle+">"+record.subject+"</a>";
		}

		date = new Date(record.datesubmitted*1000);
		var outHour = date.getHours();
		var outMin = date.getMinutes();
		var pmam = "AM"
	    if (outHour >12){newHour = outHour-12;outHour = newHour; pmam = "PM"}
		if (outMin<10){outMin="0"+outMin;}

		date = (ce.getMonth(date.getMonth()+1,true)) + " " +date.getDate()+ ", "+ date.getFullYear()+ " @ "+outHour+":"+outMin+" "+pmam;

        if (record.priority==1){
			priorityclass= "tickets-priority-1";
		}else if(record.priority==2){
			priorityclass= "tickets-priority-2";
		} else {
			priorityclass= "tickets-priority-3";
		}

        title = "<span class='"+priorityclass+"'></span><span style='color:#999;'>#"+recordId+attachment+"</span> <span style='color:#666;font-weight:bold;'>"+ subject + "</span>";
        title += "<div style='padding-top:2px;'><img qtip='" + record.method_tooltip + "' src='"+relativePath+"templates/admin/images/ticket/method-"+record.method+".png' width='10' height='10' /> from <span style='color:#33CCFF;'>"+customerName+"</span> posted on "+date+"</div>";

        return title;

    }

	ticketlist.renderAssignedTo = function(value, record, el) {
		var html = "", ratingLabel = "";
		html =  lang("Assigned to") + " <b>" + record.assignedtoname+"</b>";
		html += "<br/>" + lang("Status") + " <b>" + record.statusname+"</b>";
		if (record.status == -1 && record.rate > 0) {
			switch (record.rate) {
				case "1":
					ratingLabel = "Outstanding";
				case "2":
					ratingLabel = "Good";
				case "3":
					ratingLabel = "Ok";
				case "4":
					ratingLabel = "Poor";
			}

			if (trim(record.feedback) != "") {
				ratingLabel = "<span style='top: 0px;cursor:pointer;border-bottom: 1px solid #DFDFDF;' qtip='"+record.feedback+"'>"+ratingLabel+"</span>";
			}
			html += " (" + ratingLabel + ")";
		}

		return html;
	}

    ticketlist.grid = new RichHTML.grid({
        el: 'ticketsgrid',
        pagingEl: 'ticketsgrid-pagination',
        buttonsEl: 'ticketsgrid-buttons',
        metaEl: 'ticketsgrid-metadata',
        url: 'index.php?fuse=support&action=getTicketList',
		baseParams: { limit: clientexec.records_per_view, dir: 'asc'},
        columns: [{
                xtype:      "expander",
	            dataIndex:  "response",
	            renderOnExpand: true,
	            renderer:	ticketlist.renderExpander
            },
            {
                id:         "cb",
                dataIndex:  "id",
                xtype:      "checkbox"
            },{
                id:         "subject",
                text:     	lang("Subject"),
                align:		"left",
                renderer:   ticketlist.renderSubject,
                dataIndex:  "subject",
                sortable: 	true
            },{
            	id:         "assignedtoname",
                text:     	lang("Assigned"),
                align:		"left",
                width:      210,
                renderer:   ticketlist.renderAssignedTo,
                dataIndex:  "assignedtoname",
                sortable: 	true
            }
        ]
    });

    $('#ticketsgrid-filter').change(function(){
    	ticketlist.grid.reload({params:{start:0,limit:$(this).val()}});
    });

	// **** listeners to grid
    $(ticketlist.grid).bind({
	    "load" : function(event,data) {
        	$('#btnDelTicket').attr('disabled','disabled');
        	$('#btnMarkSpam').attr('disabled','disabled');
        	$('#btnCloseTicket').attr('disabled','disabled');

	    },
	    "rowselect": function(event,data) {
	        if (data.totalSelected > 0) {
	        	$('#btnDelTicket').removeAttr('disabled');
	        	$('#btnMarkSpam').removeAttr('disabled');
	        	$('#btnCloseTicket').removeAttr('disabled');
	        } else {
	        	$('#btnDelTicket').attr('disabled','disabled');
	        	$('#btnMarkSpam').attr('disabled','disabled');
	        	$('#btnCloseTicket').attr('disabled','disabled');
	        }
	    }
    });

    // **** lets bind our buttons
    $('#btnDelTicket').click(function () {
    	if ($(this).attr('disabled')) { return false; }
    	RichHTML.msgBox(lang('Are you sure you want to delete the selected ticket(s)'),
    		{
    			type:"prompt",
    			buttons: {  button1:{text:"yes"}, button2:{text:"no"}, button3:{text:"cancel",type:"cancel"} }
    		}, function(result) {
				if(result.btn === "yes") {
			    	ticketlist.grid.mask();
					$.post("index.php?fuse=support&action=DeleteTickets", {ids:ticketlist.grid.getSelectedRowIds()},
					   function(data){
	   						ticketlist.grid.reload({params:{start:0}});
	   						callTicketSummaries();
					});
				}
			});
    });

    $('#btnCloseTicket').click(function () {
    	if ($(this).attr('disabled')) { return false; }
    	RichHTML.msgBox(lang('Are you sure you want to close the selected ticket(s)'),
    		{
    			type:"prompt",
    			buttons: {  button1:{text:"yes"}, button2:{text:"no"}, button3:{text:"cancel",type:"cancel"} }
    		}, function(result) {
				if(result.btn === "yes") {
			    	ticketlist.grid.mask();
					$.post("index.php?fuse=support&action=UpdateTicketStatus", {newstatus:"-1",ids:ticketlist.grid.getSelectedRowIds()},
					   function(data){
	   						ticketlist.grid.reload({params:{start:0}});
	   						callTicketSummaries();
					});
				}
			});
    });


    // **** lets bind our buttons
    $('#btnMarkSpam').click(function () {
    	if ($(this).attr('disabled')) { return false; }
    	RichHTML.msgBox(lang('Are you sure you want to prevent tickets from being created from the selected ticket(s) email addresses?'),
    		{
    			type:"prompt",
    			buttons: {  button1:{text:"yes"}, button2:{text:"no"}, button3:{text:"cancel",type:"cancel"} }
    		}, function(result) {
				if(result.btn === "yes") {
			    	ticketlist.grid.mask();
					$.post("index.php?fuse=support&action=AddEmailAsSpam", {ids:ticketlist.grid.getSelectedRowIds()},
					   function(data){
	   						ticketlist.grid.reload({params:{start:0}});
	   						callTicketSummaries();
					});
				}
			});
    });

    new Ext.ToolTip({
        target: 'ticketsearchinput',
        anchor: 'top',
        autoHide: true,
        dismissDelay:3500,
        anchorOffset: 1, // center the anchor on the tooltip
        html: lang('Search tickets by subject and messages.  Four character minimum')
    });

    new Ext.form.ComboBox({
        transform: 'searchtype',
        id:'searchtype',
        typeAhead: true,
        triggerAction: 'all',
        width:100,
        editable: false,
        forceSelection:true,
        listeners: {
            'select' : function (cb, record) {

            }
        }
    })

    //create the combo for refresh intervals
    new Ext.form.ComboBox({
        transform: 'refreshgridrate',
        typeAhead: true,
        triggerAction: 'all',
        width:135,
        editable: false,
        forceSelection:true,
        listeners: {
            'select' : function (cb, record) {
                ticketlist.intervalRate = parseInt(cb.getValue());
                if (ticketlist.intervalid!=0)  {
                    //cancel interval
                    clearInterval(ticketlist.intervalid);
                    ticketlist.intervalid = 0
                }

                if (ticketlist.intervalRate> 0) {
                    ticketlist.intervalRate = ticketlist.intervalRate * 60000;
                    ticketlist.intervalid = setInterval("ticketlist.grid.reload()",ticketlist.intervalRate);
                }
            }
        }
    });

	ticketlist.PopulateTicketFilters(defaultfiltername,ticketlist.iscustom, true);

    setTimeout("ticketlist.updateCounts()", 1500);
    ticketlist.updateCounts = function()
    {
    	$.ajax({
          url: "index.php?action=getTodaysTicketCounts&fuse=support",
	      dataType: 'json',
	      async: true,
	      success: function(json) {
			 $("#openedtoday").html(json.items.opened);
			 $("#closedtoday").html(json.items.closed);
			 $("#repliedtoday").html(json.items.replied);
			 $("#ratedtoday").html(json.items.rated);
	      }
	    });
    }


});
