/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
| Support Center :: alteredCart.com
| All code developed by Bill Brewer
| Copyright (c)2009 alteredCart            
| Bill Brewer <bill@alteredcart.com> | All rights reserved.
| This code is licensed for use on a single server.
| This code is licensed for use by the original purchaser only.
| Full license :: www.alteredcart.com/license.php
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/

var attachmentsCount = 1;
var searchKBInterval = null;
var err_creator_must_be_logged = 'The creator of this ticket must be logged in to download attachments.'

function supportAddTags(elem, starttag, endtag){

	elem = ac.$(elem);
	var scrollpos = elem.scrollTop;

	if (elem.setSelectionRange) {
	
 		elem.value = elem.value.substring(0,elem.selectionStart) + starttag + elem.value.substring(elem.selectionStart,elem.selectionEnd) + endtag + elem.value.substring(elem.selectionEnd,elem.value.length)
  	
		} else {

		var selectedText = document.selection.createRange().text;

		if (selectedText != "") {
			var newText = starttag + selectedText + endtag;
			document.selection.createRange().text = newText;
			}
		}

		// Preserve the scroll position //
		elem.scrollTop = scrollpos;
	}

function addAttachmentInput(){

	var attachments = ac.$('addAttachments').getElementsByTagName('input');

	// The last element is empty //
	if (attachments.length > 0 && attachments[attachments.length-1].value == '')
		return;

	ac.createElem({node:'input', type:'file', name:'attachment'+attachmentsCount, onclick:addAttachmentInput, add_br:true}, 'addAttachments');
	attachmentsCount++;

	if (typeof(supportUploadWinLayout) == 'function')
		supportUploadWinLayout();

	}

function searchKBAJAX(){

	var str = ac.$('post_descr').value;
	
	// Check if the customer is posting confidential data //
	if (str.match(/\bftp\b|\blogin\b|\bpass\b|\bpassword\b|\badmin\b|\busername\b/i))
		ac.$('secureDataWarning').style.display = '';

	if (str.length < 20)
		return;
		
	var params = 'q='+encodeURIComponent(str);

	// Query the db //
	ac.updateSuggested = function(html){ ac.$('searchKBResults').innerHTML = html; };
	ac.ajax({url:'support.php?ajax_function=searchkb', parameters:params, method:'POST', returned:'text', return_func:ac.updateSuggested});

	}

function displayTab(selected){
	
	// Tab is already selected //
	if (ac.$(selected).className == 'selectedTab')
		return;

	// Get all of the available options //
	var divs = ac.$('ticketTabs').getElementsByTagName('div');
	
	for (i = 0; i < divs.length; i++){
		
		if (!divs[i].id)
			continue;
			
		// Save the current soon to be previous size //
		if (ac.$(divs[i].id).className == 'selectedTab' && divs[i].id != selected){
			prevSize = ac.$(divs[i].id+'_display').offsetHeight;
			prevID = divs[i].id;
		}

		if (divs[i].id == selected){
			
			ac.$(divs[i].id).className = 'selectedTab';
			ac.$(divs[i].id).innerHTML = ac.$(divs[i].id).innerHTML.replace(/t-i-/g, 't-a-'); // Set the active images //
				
				} else {

			ac.$(divs[i].id).className = 'inactiveTab';
			ac.$(divs[i].id).innerHTML = ac.$(divs[i].id).innerHTML.replace(/t-a-/g, 't-i-'); // Set the inactive images //
			
			}
		}
		
		contentsDiv = ac.$('ticketsContentsDisplay');
		offset = contentsDiv.offsetHeight - prevSize;
		selectedDiv = ac.$(selected+'_display');
		previousDiv = ac.$(prevID+'_display');
		
		//contentsDiv.style.overflow = 'hidden';

		// Get the size of the selected div //
		selectedDiv.style.postition = 'absolute';
		selectedDiv.style.left = '-1000px';
		selectedDiv.style.height = '';
		selectedDiv.style.display = '';
	
		newsize = selectedDiv.offsetHeight;
	
		ac.changeOpacity(0, selectedDiv.id);
		selectedDiv.style.postition = 'static';
		
		selectedDiv.style.height = '0px';
		
		ac.changeSize({id:selectedDiv.id, start:0, end:newsize, xy:'y', millisec:200});
		ac.changeSize({id:previousDiv.id, start:prevSize, end:0, xy:'y', millisec:200});
		
		ac.fade(previousDiv.id, 100, 0, 200);
		setTimeout(function(){ac.fade(selectedDiv.id, 0, 100, 300);}, 200);
		
		// This will prevent the contents from being hidden if the texta area size is changed //
		setTimeout(function(){selectedDiv.style.height = '';}, 500);
			
			if (selected == 'post_reply')
				ac.$('post_descr').focus();

		//setTimeout("contentsDiv.style.overflow = 'display'", 300);

		}

function supportQuote(dataid, ticketid){

	var params = 'dataid='+encodeURI(dataid)+'&ticketid='+encodeURI(ticketid)+'&section=tickets&action=load_quote';
	
	ac.current_desc = document.post_reply_ticket.description.value;
	
	document.post_reply_ticket.description.value = 'Please wait while loading quoted text...';

	// Load the quote //
	ac.loadQuote = function(html){ 
		document.post_reply_ticket.description.value = ac.current_desc+"\n\n"+html; 
		ac.current_desc = '';
		document.post_reply_ticket.description.scrollTop = document.post_reply_ticket.description.scrollHeight;		
	};

	ac.ajax({url:'support.php', parameters:params, method:'POST', returned:'text', return_func:ac.loadQuote});
	
	displayTab('post_reply');
	ac.scrollToElement('singleTicketDisplay');

	}

function showHideElement(id, effect){

		// Grow the object //
		if (ac.$(id).style.display == 'none'){
			
			if (effect){

				newsize = ac.offsetHeightHidden(id);
				ac.$(id).style.height = '0px';
				ac.$(id).style.overflow = 'hidden';
				ac.$(id).style.display = '';
				ac.changeSize({id:id, start:0, end:newsize, xy:'y', millisec:300});

			} else {

					ac.$(id).style.display = '';

				}
			
			// Shrink the object //
			} else {
				
				if (effect)
					ac.changeSize({id:id, start:ac.$(id).offsetHeight, end:0, xy:'y', millisec:300});
						else
					ac.$(id).style.display = 'none';
		}
	}

function checkUncheckFields(field, elem){

	var fields = document.getElementsByName(field);

		if (elem.checked == true){
			for (i = 0; i < fields.length; i++)
				fields[i].checked = true;
				
		} else {
		
			for (i = 0; i < fields.length; i++)
				fields[i].checked = false ;
		}
	}

function supportValidateEmail(email, alerterr){
	
	if (email.match(/^[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}$/i))
		return true;
		
	if (alerterr)
		alert('Email address is invalid.');
		
	return false;
	
	}

function checkEditForm(){

var err = '';

	// Make sure the fields are filled //
	if (!document.edit_ticket_form.change_subject.value)
		err = "Subject: is a required field.\n\n";
		
	if (!document.edit_ticket_form.change_name.value)
		err = err+"Name: is a required field.\n\n";
	
	if (!document.edit_ticket_form.change_email.value || !supportValidateEmail(document.edit_ticket_form.change_email.value, false))
		err = err+"Email address is invalid.\n";
		
		if (!err)
			document.edit_ticket_form.submit();
				else
			alert(err);
	}

function supportPreviewPost(post){
	
	ac.createModal({div:'previewPost'});
	ac.$('previewPost').innerHTML = '';
	
	// Background preview image //
	if (!ac.savedPreviewBackImg)
		ac.savedPreviewBackImg = ac.$('previewPost').style.backgroundImage;
		
	ac.$('previewPost').style.backgroundImage = ac.savedPreviewBackImg;

	var params = 'post='+encodeURI(post)+'&ticketid='+encodeURI(ticketid)+'&section=tickets&action=preview_post&ajax_function=preview_post';

	ac.loadPreview = function(html){ 
		ac.$('previewPost').innerHTML = html;
		ac.$('previewPost').style.backgroundImage = '';
	};

	ac.ajax({url:'support.php', parameters:params, method:'POST', returned:'text', return_func:ac.loadPreview});

	}

function supportViewFile(attachmentid, ticketid){

	ac.createModal({div:'quickView'});
		ac.$('quickViewContents').innerHTML = '';

	// Background preview image //
	if (!ac.savedPreviewBackImg)
		ac.savedPreviewBackImg = ac.$('quickView').style.backgroundImage;

	ac.$('quickView').style.backgroundImage = ac.savedPreviewBackImg;

	var params = 'attachmentid='+encodeURI(attachmentid)+'&ticketid='+encodeURI(ticketid)+'&section=tickets&action=quick_view';

	ac.quickView = function(html){
		ac.$('quickViewContents').innerHTML = html;
		ac.$('quickView').style.backgroundImage = '';
	};

	ac.ajax({url:'support.php', parameters:params, method:'POST', returned:'text', return_func:ac.quickView});

	}

function supportPrevMessage(id){

	ac.$('previousMessage').innerHTML = ac.$('prev_message'+id).innerHTML;
	ac.createModal({div:'previousMessage'});
	
	}

function addDynamicSort(){

	var th = ac.$('ticketsDisplay').getElementsByTagName('th');
	
	for (i=0; i < th.length; i++){
		
		if (!th[i].id)
			continue;
			
		var name = th[i].id.substr(2, th[i].id.length);
		
		// Select the current sorting element //
		if (ticketSort == name){
			ac.$(th[i].id).innerHTML = ac.$(th[i].id).innerHTML+' <img id="sort'+name+'" src="'+ac.ImagesDir+'/sort_'+ticketSortDirection+'.png" alt="" />';
		
			} else {
		
		// Add in the sort image //
		ac.$(th[i].id).innerHTML = ac.$(th[i].id).innerHTML+' <img id="sort'+name+'" style="display:none;" src="'+ac.ImagesDir+'/sort_ASC.png" alt="" />';
		
		}

		ac.addEvent(ac.$(th[i].id), 'mouseover', function(){ var name = this.id.substr(2, this.id.length); this.className='selected'; if (ticketSort == name) return; ac.$('sort'+name).style.display = ''; });
		ac.addEvent(ac.$(th[i].id), 'mouseout', function(){ var name = this.id.substr(2, this.id.length); this.className=''; if (ticketSort == name) return; ac.$('sort'+name).style.display = 'none'; });
		ac.addEvent(ac.$(th[i].id), 'mousedown', function(){ window.location='support.php?section=tickets&sort='+this.id.substr(2, this.id.length); });

		}
	}

function submitContactForm(){

	formObj = document.supportForm;
	
	// Check the form //
	if (!formObj.name.value){
		alert('Name is required.');
			return;
	}
	
	if (!formObj.email.value){
		alert('Email is required.');
			return;
	}
	
	if (!formObj.subject.value){
		alert('Subject is required.');
			return;
	}
	
	if (!formObj.description.value){
		alert('Question, Comment or Feedback is required.');
			return;
	}

	ac.$('submitImg').style.display = '';
	ac.$('submitButtons').style.display = 'none';
	formObj.submit();

	}

function supportReportBug(){
	
	ac.$('contactTable').style.display = '';
	
	}

function hideTicketOptions(){

	var fields = document.getElementsByName('ticketids[]');

		for (i = 0; i < fields.length; i++){
			
			if (fields[i].checked == true){
				ac.unmask('ticketOptions');
					return;

			}
		}

	ac.mask('ticketOptions');
	
	}


/* Image Display */
function elemScroll(opt){

 // @ direction [up, down, left, right], container_div [the div to adjust the style (top, bottom, left, right)], imgid [scroll to a preset image]

	if (sliding)
		return;
	
	// Current position //
	if (!current_pos)
		current_pos = parseInt(ac.$(opt.container_div).style.top);
		
	// Scroll to a specific image //
	if (opt.imgid){

	ac.$(opt.container_div).style.top = '0px';
	current_pos = 0;

	sliding = true;

	var end = 0;

	for (var x=0; x<images.length; x++){
	
		if (images[x].id == opt.imgid){

			current_image = x;
			break;
		}
	
		end += (ac.$(images[x].id).offsetHeight + image_spacing);
	}
	
		end = (current_pos - end);

		ac.changeStyle({id:opt.container_div, start:current_pos, end:end, style_attr:'top', millisec:600});
		setTimeout("sliding = false", 610);

		current_pos = end; // Update the position to what it will be after the 'slide' //	
		return;		
		
	}

	if (opt.direction == 'up'){

		if (current_image == 0)
			return;
			
		sliding = true;

		// Determine how large the previous image is, and scroll as necessary //
		var height = ac.$(images[current_image-1].id).offsetHeight;
		var end = current_pos + image_spacing + height;

		ac.changeStyle({id:opt.container_div, start:current_pos, end:end, style_attr:'top', millisec:300});
		setTimeout("sliding = false", 310);

		current_pos = end; // Update the position to what it will be after the 'slide' //
		current_image--;			

	}

	else if (opt.direction == 'down'){

		if (current_image == total_images-1)
			return;

		sliding = true;

		// Determine how large the current image is, and scroll as necessary //
		var height = ac.$(images[current_image].id).offsetHeight;
		var end = current_pos - image_spacing - height;

		ac.changeStyle({id:opt.container_div, start:current_pos, end:end, style_attr:'top', millisec:300});
		setTimeout("sliding = false", 310);

		current_pos = end; // Update the position to what it will be after the 'slide' //
		current_image++;

		}

		if (current_image == 0)
			ac.$('imageUP').style.display = 'none';
				else
			ac.$('imageUP').style.display = '';

		if (current_image == total_images-1)
			ac.$('imageDOWN').style.display = 'none';
				else
			ac.$('imageDOWN').style.display = '';

	}
	
function displayImage(attachmentid){

	// Set the dimensions of the main image display //
	ac.$('imageDisplaySectionT').style.height = (ac.$('imagesDisplay').offsetHeight - 25)+'px';
	ac.$('imageDisplaySectionT').style.width = (ac.$('imagesDisplay').offsetWidth - 275)+'px';

	// Reset the display //
	ac.$('imageDisplaySection').innerHTML = '';

	// Display the loading image //
	ac.$('imageDisplaySection').style.backgroundImage = "url('"+ac.ImagesDir+"/loading_a.gif')";

	// Create the image //
	ac.createElem({node:'img', src:catalog_loc+'/support.php?section=tickets&action=file&modal=1&attachmentid='+encodeURI(attachmentid)+'&ticketid='+encodeURI(ticketid)}, 'imageDisplaySection')
	// @ properties = node, input[form], type, size, value, name, id, className //

	// Reset the images //
	for (var x=0; x<images.length; x++){		
		ac.$(images[x].id).style.backgroundColor = '';
		}

	// Change the background of the selected //
	ac.$('imgid'+attachmentid).style.backgroundColor = '#404040';
	
	// Give the image 3 seconds to load, and then remove the loading image //
	setTimeout("ac.$('imageDisplaySection').style.backgroundImage=''", 3000);

	}

function selectDisplayImg(attachmentid){

	ac.createModal({div:'imagesDisplay'});
	displayImage(attachmentid);
	elemScroll({direction:'down', container_div:'numbers', imgid:'imgid'+attachmentid});

	}
	
function supportImgZoom(dir){

	// Image id //
	var imgid = ac.$('imageDisplaySection').getElementsByTagName('img');
	
	var obj = ac.$(imgid[0].id);
	
		if (dir == 'in'){
		
			obj.height = obj.height * 1.2;
			obj.width = obj.width * 1.2;
		}
		
		else if (dir == 'out'){
		
			if ((obj.height * .8) < 1 || (obj.width * .8) < 1)
				return;	
	
			obj.height = obj.height * .8;
			obj.width = obj.width * .8;
		}
	}

/* Shortcuts */
ac.shortcuts = {
	
	monitorShortcutKeys: function(e){

	e = e || window.event;

	if (!e.shiftKey || ac.disableShortcut)
		return;

	// Reply Tab //
	if (e.keyCode == 82){
		displayTab('post_reply');
		ac.scrollToElement('ticketTabs');
		return;
		}
	// General Tab //
	else if (e.keyCode == 71){
		if (!ac.$('general'))
			return;
		displayTab('general');
		ac.scrollToElement('ticketTabs');
		return;
		}
	// Edit Tab //
	else if (e.keyCode == 69){
		if (!ac.$('edit'))
			return;
		displayTab('edit');
		ac.scrollToElement('ticketTabs');
		return;
		}
	else if (e.keyCode == 78){
		if (!ac.$('add_note'))
			return;
		displayTab('add_note');
		ac.scrollToElement('ticketTabs');
		return;
		}
	else if (e.keyCode == 67){
		if (!ac.$('customer_info'))
			return;
		displayTab('customer_info');
		ac.scrollToElement('ticketTabs');
		return;
		}
	else if (e.keyCode == 80){
		if (!ac.$('charged_points'))
			return;
		displayTab('charged_points');
		ac.scrollToElement('ticketTabs');
		return;
		}
	else if (e.keyCode == 65){
		displayTab('post_access');
		ac.scrollToElement('ticketTabs');
		return;
		}
	},

 	addEHandler: function(formElem){
	
	if (!formElem)
		return;

	for (x = 0; x < formElem.length; x++){
	
		//console.log(formElem[x].name+' '+formElem[x].type);

		if (formElem[x].type == 'text' || formElem[x].type == 'textarea'){
	
		ac.addEvent(formElem[x], 'focus', function(){ac.disableShortcut = true;});
		ac.addEvent(formElem[x], 'blur', function(){ac.disableShortcut = false;});
			}
		}	
	}
	
	}


/* Chat */
ac.chat = {

	contact:function(){

	// Check the fields //
	var name = document.start_chat.name.value;
	var email = document.start_chat.email.value;
	
	if (!name || !email){
		alert('Name and email are required');
		return;
	}

	var params = 'section=chat&action=contact&name='+encodeURI(name)+'&email='+encodeURI(email);

	// Load the posted text //
	ac.contactReceived = function(response){
	
		var r = response.split("\n");
		
			if (r[0] == 'S'){

				ac.chatSessionId = r[1];
				ac.$('chatDialog').innerHTML = r[2];
				ac.$('chatMainWindow').style.display = '';
				ac.$('chatStartForm').style.display = 'none';
				ac.chat.fetch();
				
			} else {
				
				alert('There was an error initializing the chat');
			}	
		};

	ac.ajax({url:'support.php', parameters:params, method:'POST', returned:'text', return_func:ac.contactReceived});
	
		},
		
	response:function(){
	
		var response = document.chat_response.response.value;
		ac.$('postingMessageWait').style.display = '';
		ac.$('postingMessageButton').style.display = 'none';
		
		if (!ac.chat.selectedChatid)
			ac.chat.selectedChatid = 0;

		var params = 'section=chat&action=post_response&dialog='+encodeURI(response)+'&chat_count='+parseInt(ac.chatCount)+'&selected_chatid='+parseInt(ac.chat.selectedChatid);

		// Load the posted text //
		ac.responseReceived = function(response){

			var r = response.split("\n");
			ac.$('postingMessageWait').style.display = 'none';
			ac.$('postingMessageButton').style.display = '';
			document.chat_response.response.value = '';

			if (r[0] == 'S'){

				ac.chat.displayResponse(response.substr(1, response.length));

			} else {
				
				alert('There was an error contacting the chat server');
			}	
		};

		ac.ajax({url:'support.php', parameters:params, method:'POST', returned:'text', return_func:ac.responseReceived});

			},
			
	displayResponse:function(response){

		var objDiv = ac.$('chatDialog');
		objDiv.innerHTML = response;		
		objDiv.scrollTop = objDiv.scrollHeight;
		
		},
			
	fetch:function(){

		var params = 'section=chat&action=fetch_response&chatCount='+parseInt(ac.chatCount);

		// Load the posted text //
		ac.fetchReceived = function(response){
	
			var r = response.split("\n");

			if (r[0] == 'S'){

				if (response.length > 3)
				ac.$('chatDialog').innerHTML = response.substr(1, response.length);
				ac.chat.fetch();

			} else {
				
			}	
		};

		ac.ajax({url:'support.php', parameters:params, method:'POST', returned:'text', return_func:ac.fetchReceived});

		}
	}