/* 
// Document: WLL Wall Animation Class
// Author: Tom Belknap
// Description: provides active content on pages to prevent page refreshes when commenting
//     This version creates a OOP class from which our functions can be pulled.
// Date: December 18th, 2009
// Requires: Scriptaculous libraries V1.8.3
*/ 


//Hide Other Actions
$('.actionbar .button:not(.red)').live('click', function() {
	$(this).siblings('.red').click();
})

$(document).ready(function() {
	if ($('#question-box').length){
		$('#order_question').attr('value', $('#LatteOrderID').text())
	}
	$('.showthisvids').each(function() {
		var theTitle = $(this).children('img').attr('alt') + " Videos";
		var theDialog = $(this).siblings('.video-popup')
		theDialog.dialog({
			title: theTitle,
			autoOpen: false,
			width: '640px', 
			closeText: '[x] close'
		});
	})
	$('#collection-list').accordion({ 
		collapsible: true, 
		active: false,
		autoHeight: false 
	});
	$('#alfred').dialog({
		modal: true,
		autoOpen: false,
		title: "May I Help You!",
		width: '600px',
		resizable: false,
		position: ['center', 50]
	})

	// Set up canned responses
	$('.canMe').draggable({revert: true});
	$('.csuberwall').find('textarea').droppable({drop: function(event, ui) {
			var newText = $(ui.draggable).text();
			if ($(this).val() != '') {
				$(this).append(' ');
			}
			$(this).append(newText);
			if ($(ui.draggable).find('input').length) {
				$(this).append($(ui.draggable).find('input').val())
			}
			$(ui.draggable).hide()
		}
	});
	$('.cs-accordion').accordion({ collapsible: true, active: false });
})
//User Selects Post Type
$('#wallPostType').live('change', function(){
	$.getJSON("/Includes/order_history.cfc?", {method: 'getSpecificOrders'}, function(data) {
		$('#specOrders').hide().html("");
		$('#itemlist').hide().html('');
		$('#specOrders').append('<option>Choose an Order...</option>');
		$.each(data, function(key, val) {
		  $('#specOrders').append('<option value="' + key + '">' + val + '</option>');
		});
		$('#specOrders').append('<option value="0">No Specific Order</option>');
		$('#specOrders:hidden').animate({width: 'toggle'});
	});
})

//User Selects Order
$('#specOrders').live('change',function(){
	var OrderNumber = $(this).children(':selected').attr('value');
	$('#itemlist').hide().html('');
	if (OrderNumber > 0){
		$.getJSON("/Includes/order_history.cfc?", {method: 'getOrderDetail', Order_ID: OrderNumber}, function(data) {
			$.each(data, function(key, val) {
			  $('#itemlist').append('<input type="checkbox" name="vehicle" value="' + key + '">' + val + '<br />');
			});
			$('#itemlist:hidden').slideDown();
		});
	}
});


//Expand Order List
$('.item-list-label').live('click', function() {
	
	$(this).next().slideToggle(function() {
		if ($(this).prev().text() == "List Items") {
			$(this).prev().text("Hide Items");
		} else {
			$(this).prev().text("List Items");
		}
	})

})

// Hover the Action Bar
$('.actionbar .button').live('mouseenter', function() {
	if ($(this).children('img').length) {
		var altText = $(this).children('img').attr('alt');
		$('.tooltip_transparent').text(altText);
		var buttonLeft = $(this).offset().left;
		var buttonTop = $(this).offset().top;
		var newLeft = buttonLeft - 70;
		var newTop = buttonTop - 74;
		$('.tooltip_transparent').css({'top' : newTop, 'left' : newLeft}).fadeIn();
	}
})


$('.actionbar').live('mouseleave', function() {
	$('.tooltip_transparent').fadeOut();
})

//Highlight Items that can be returned and show return information
$('#return-toggle:not(.red)').live('click', function() {
	if(!$('.isReturn').length){
		$(this).addClass('red');
		$(this).children('img').attr('alt', 'Hide Return Information')
		$('.order-preview tr.header').prepend('<td style="display:none" class="isReturn">Eligible for Return</td>')
		$('.returnable').prepend('<td style="display:none" class="isReturn yes">&#10004;</td>')
		$('.item-listing').not('.returnable').prepend('<td style="display:none" class="isReturn no">X</td>')
		
		$('.order-preview tr:not(.header)').not(':has(.isReturn)').prepend('<td style="display:none" class="isReturn" colspan="1"></td>')
	
		$('.isReturn').css({opacity: '0.0'}).animate({width: 'toggle'}, function(){
			$(this).animate({opacity: '1.0'}, function() {
					$('.no-return').slideDown();
					$('.isReturn').css({display: 'block'})
				});
		})
		
	}
});

$('#return-toggle.red').live('click', function() {
	$('p.no-return').slideUp(function() {
		$('td.isReturn').animate({width: 'toggle'}, function() {
			$(this).remove();
		})
	});
	$(this).removeClass('red');
	$(this).children('img').attr('alt', 'Show Return Information')
});

//Show/Hide Support Documents
$('#tech-toggle').live('click', function() {
	$('p.support-document').slideToggle(function(){
		$(this).children('a').animate({'background-color' : '#DAA'}, 800
		).animate({'background-color' : '#FFF'}, 800)
	})
	$(this).toggleClass('red');
	if ($(this).children('img').attr('alt') == "Get Technical Help") {
		$(this).children('img').attr('alt', "Hide Technical Help")
		$('#question-type').attr('value', '2')
		// $('#question-box').slideDown();
		$('#faq-box').slideDown();

		
	} else {
		$(this).children('img').attr('alt', "Get Technical Help")
		// $('#question-box').slideUp();
		$('#faq-box').slideUp();
	}
})

//Reveal Alfred 
$('#alfred-toggle').live('click', function() {
	$('#alfred').dialog('open');
})


/*
      _       _____     ________  _______     ________  ______    
     / \     |_   _|   |_   __  ||_   __ \   |_   __  ||_   _ `.  
    / _ \      | |       | |_ \_|  | |__) |    | |_ \_|  | | `. \ 
   / ___ \     | |   _   |  _|     |  __ /     |  _| _   | |  | | 
 _/ /   \ \_  _| |__/ | _| |_     _| |  \ \_  _| |__/ | _| |_.' / 
|____| |____||________||_____|   |____| |___||________||______.'  
                                        
*/

//User Selects Collection
$('#collection-list').live('accordionchangestart', function(event, ui) {
	// $('this').accordion('disable');
	if (!ui.newHeader.attr('data-product')) {
		var collection = $(ui.newHeader).attr('rel');
		$(ui.newContent).html('');
		getAlfred(collection, ui)
	} else {
		$(this).find('select').data({ui: ui});
	}
})

//User Selects Product From Collection
$('.alfred-product').live('change', function() {
	var ui = $(this).data().ui;
	var collection = $(ui.newHeader).attr('rel');
	var product = $(this).val();
	$(this).nextAll().remove();
	getAlfred(collection, ui, product);
})

function getAlfred(collection, ui, product) {
	product = product || ""
	$.ajax({
		url: '/ajax/alfred.cfc',
		dataType: 'json',
		data: {
			method: 'getRelationshipsByCollection',
			collection: collection,
			product: product
		},
		success: function(data) {
			
			
			var that = $(this);
			if (data[0]) {
				$.each($(data).distinct("id"), function(i, category) {
					$(ui.newContent).append('<span class="qc">' + category.name + '</span>');
					$(ui.newContent).append('<div class="smc"></div>');
					$.each($(category.symptoms).distinct("id"), function(i, symptom) {
						var smcontainer = $(ui.newContent).find('.smc:last');
						$(smcontainer).append('<span class="sm">' + symptom.name + '</span>');
						$(smcontainer).append('<div class="slc"></div>');
						var sols = $.grep($(symptom.solutions), function(n, i) {
									 	 return n.solutionid != 0
									  })
									
						$.each($(sols).distinct("solutionid"), function(i, solution){
							var slcontainer = $(ui.newContent).find('.slc:last');
							var tmpTitle = solution.solutionname.match(/{title:(.*)}/)
							if(tmpTitle) {
								var title = tmpTitle[1]								
							} else {
								var title = "Solution " + (i + 1);
							}
							var content = solution.solutionname.replace(/{title:(.*)}/, '');
							$(slcontainer).append('<span class="slt">' + title + '</span>')
							// $(slcontainer).append('<span class="sl">' + content + '</span>');
							var slnew = document.createElement('span');
							$(slnew).addClass('sl').html(content);
							if (solution.videoid != 0) {
								$(slnew).append('<span class="video-link">Video: <a target="_blank" href="/videos.cfm?playvidid=' + solution.videoid + '">' + solution.video + '</a></span>')
							}
							if (solution.supportdocumentid != 0) {
								$(slnew).append('<span class="document-link">Document: <a target="_blank" href="/' + solution.supportdocumentpath + '">' + solution.supportdocument + '</a></span>')
							}
							$(slcontainer).append($(slnew));
						})
					})
					
				})
			} else {
				$(ui.newContent).append('No content found.')
			}
			$(that).accordion('resize');
		}
	});
}

//User Selects Question Category
$('.qc').live('click', function() {
	var myChild = $(this).next('div.smc');
	$(myChild).slideToggle()
})

//User Selects Symptom
$('.sm').live('click', function() {
	var myChild = $(this).next('div.slc');
	var that = $(this)
	//$(myChild).slideToggle();
	if($(myChild).children().length) {
		$('#collection-list').transitionFw($(myChild))
		$('#collection-list').data({
			returnSpot: that
		})
	}
})

//Back
$('#back-button').live('click', function() {
	$('#solution-window').transitionBw('#collection-list');
})

$.fn.distinct = function(attribute) {
  var goods = [];
  var exist = [];
  var that = $(this);
  $.each(that, function(a, b) {
    var thid = this[attribute];
    if ($.inArray(thid, exist) < 0) {
      exist.push(thid);
      goods.push(that[a]);
    }
  })
  return goods
}

$.fn.transitionFw = function(dom) {
	var newLeft = ($(this).outerWidth() * -1) - 50;
	var domWidth = $(this).outerWidth() + 25;
	var startRight = newLeft * -1;
	var container = $('#solution-window');
	$(container).append($(dom))
	$(this).css("position", "relative");
	$(container).css({
		left: startRight,
		width: domWidth,
		display: "block"
	})
	$(dom).css({
		top: "0px",
		display: "block"
	})
	$(this).animate({
		left: newLeft
	})
	$(container).animate({
		left: 0
	}, function() {
		$('#back-button').show();
		$('#alfred').animate({
			height: '600px'
		})
	})
}

$.fn.transitionBw = function(dom) {
	var newRight = $(dom).outerWidth() + 60;
	var oldContainer = $('#collection-list').data().returnSpot;
	var returnContent = $(this).children();

	$('#back-button').hide();
	$(dom).animate({
		left: 0
	})
	$(this).animate({
		left: newRight
	}, function() {
		$(this).hide();
		$(returnContent).hide();
		$('#alfred').css('height', '');
		$(oldContainer).after($(returnContent))
	})
	var symcount = $('#collection-list').data().symcount || 0;
	symcount++;
	$('#collection-list').data('symcount', symcount)
	if (symcount == 5) {
		var wantsHelp = confirm("It seems you're having trouble finding what you're looking for. Would you like some extra help?");
		if (wantsHelp) {
			var userQuestion = prompt('Enter a question to send to customer service');
		}
	}
}


//Show Frieght Claim Policy
$('#launch-freight').live('click', function() {
	$('#freight-dialog').dialog({title: "Freight Claim Policy", 
									closeText: '[x] close'
								})

})


//Show/Hide Ask a Question 
$('#question-toggle').live('click', function() {
	$('#question-type').attr('value', '1')
	$('#question-box').slideToggle()
	$(this).toggleClass('red')
})

// Show videos for item
$('.showthisvids').live('click', function() {
	var theDialog = "#" + $(this).attr('dialog');
	$(theDialog).dialog("open");
})

// AJAX Add comment

$('.csuberwall input[type=submit]').live('click', function() {
	var theForm = $(this).parents('.csuberwall');
	var wallId = theForm.children('input[name=CustServWallID-ajax]').val();
	var commentText = theForm.find('textarea').val();

	$.ajax({
		url: '/Includes/custserv_functions.cfc', 
		type: 'post', 
		data: {
			method: 'qry_insert_wall_comment', 
			memberid: 884, 
			custservwallid: wallId, 
			CustServWallCommentText: commentText, 
			CustServWallCommentHide: 0, 
			dsource: 'newlattelove'
		}
	})
	window.location.reload(true);
	return false;
})

// Class declaration:
function wllWall_class() {
	this.pageVars = getUrlVars();
}

wllWall_class.prototype.wllWA_Comment = function(post) {
	// var target = document.getElementById('wall'+post);
	
	// Do we already have a comment field? If so, bypass it:
	var testform = document.getElementById('wallcommform');
	if(testform == null) {
		// Are we in Chromium or some other browser that works properly?
		var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
		// Build form elements
		var form = document.createElement('FORM');
		form.setAttribute('method', 'post');
		form.setAttribute('action', window.location.href);
		form.setAttribute('name', 'wallcommform');
		form.setAttribute('id', 'wallcommform');
		form.setAttribute('style', 'display:none');
		if(!is_chrome) {
			form.setAttribute('style', 'display:none');
		}
		// processcom hidden field
		var processcom = document.createElement('INPUT');
		processcom.setAttribute('type', 'hidden');
		processcom.setAttribute('value', '1');
		processcom.setAttribute('name', 'processcom');
		// WallID hidden field
		var WallID = document.createElement('INPUT');
		WallID.setAttribute('type', 'hidden');
		WallID.setAttribute('value', post);
		WallID.setAttribute('name', 'WallID');
		// myaccountcommentformfield div
		var myaccountcommentformfield = document.createElement('DIV');
		myaccountcommentformfield.setAttribute('id', 'myaccountcommentformfield');
		// WallCommentText textarea form element
		var WallCommentText = document.createElement('TEXTAREA');
		WallCommentText.setAttribute('name', 'WallCommentText');
		WallCommentText.setAttribute('id', 'WallCommentText');
		WallCommentText.setAttribute('class', 'comment');
		WallCommentText.setAttribute('cols', '45');
		WallCommentText.setAttribute('rows', '3');
		WallCommentText.setAttribute('style', 'color: #aaa;');
		WallCommentText.innerHTML = 'Respond to this!';
			// Error checking and character counting events
			addEvent(WallCommentText, 'blur', function() { wll.dTextOnBlur(this); });
			addEvent(WallCommentText, 'focus', function() { wll.dTextOnFocus(this); });
			addEvent(WallCommentText, 'keyup', function() { wll.limitText(this, document.getElementById('commCount'), 500); });
		// Wrapper div for submit and cancel buttons
		var myaccountcenterrightbutton = document.createElement('DIV');
		myaccountcenterrightbutton.setAttribute('id', 'myaccountcenterrightbutton');
		// Character Counting Div and Input:
		var charCount = document.createElement('DIV');
		charCount.setAttribute('id', 'commentcount');
		charCount.setAttribute('class', 'countdown');
		var commCount = document.createElement('INPUT');
		commCount.setAttribute('readonly', 'readonly');
		commCount.setAttribute('type', 'text');
		commCount.setAttribute('name', 'commCount');
		commCount.setAttribute('id', 'commCount');
		commCount.setAttribute('size', '2');
		commCount.setAttribute('value', '500');
		charCount.innerHTML = '500 character limit - <input readonly type="text" name="commCount" id="commCount" size="2" value="500">characters left.';
		// Submit button
		var submitb = document.createElement('INPUT');
		submitb.setAttribute('type', 'button');
		submitb.setAttribute('value', 'Comment');
		submitb.setAttribute('class', 'button');
		addEvent(submitb, 'click', function() { wll.checkComment(document.getElementById('WallCommentText')) });
		// Cancel button: destroys form if poster changes mind
		var cancelb = document.createElement('INPUT');
		cancelb.setAttribute('type', 'button');
		cancelb.setAttribute('name', 'Cancel');
		cancelb.setAttribute('value', 'Ø Cancel');
		cancelb.setAttribute('class', 'red button');
		// Add the hideComment() function to the cancel button:
		// addEvent(cancelb, 'click', function() { wll.hideComment(); });
		var spacer = document.createElement('DIV');
		spacer.setAttribute('style','display: inline; width: 10px;');
		spacer.innerHTML = '&nbsp;';
		/* Add an achor to the form to push the window down:
		var anch = document.createElement('A');
		anch.setAttribute('name', 'commform'+post);
		anch.setAttribute('id', 'commform'+post); */
		
		// Tuck 'em in, say goodnight:
		myaccountcenterrightbutton.appendChild(cancelb);
		myaccountcenterrightbutton.appendChild(spacer);
		myaccountcenterrightbutton.appendChild(submitb);
		myaccountcommentformfield.appendChild(WallCommentText);
		myaccountcommentformfield.appendChild(myaccountcenterrightbutton);
		myaccountcommentformfield.appendChild(charCount);
		form.appendChild(processcom);
		form.appendChild(WallID);
		form.appendChild(myaccountcommentformfield);
		
		// Finally, the target div:
		return form
		//window.location = '#commform'+post;
		// Scriptaculous effects to animate the form (Effect.appear)
		//     and scroll to the comment form
		// if(!is_chrome) {
		// 	Effect.Appear('wallcommform', { duration: 1.2 });
		// }
		// Effect.ScrollTo('w'+post, { duration: 1.2, offset: -10 });
	}
}

var wll = {
	hideComment: function(){
		$('#wallcommform').slideUp();
	}
}

wllWall_class.prototype.destroyComment = function() {
	//Effect.Fade('wallcommform', { duration: 3.0, afterFinish: destroyComment(elm) });
	var comment = document.getElementById('wallcommform');
	var parent = comment.parentNode;
	parent.removeChild(comment);
}


//Toggle Comment
$('.addComment').live('click', function() {
	var post = $(this).attr('data-post');
	if ($('#wallcommform').length){
		$('#wallcommform').slideUp(function(){
			$(this).remove()
			var newHTML = wll.wllWA_Comment(post);
			$('.commentList#' + post).append(newHTML);
			$('#wallcommform').slideDown();
		});
		} else {
			var newHTML = wll.wllWA_Comment(post);
			$('.commentList#' + post).append(newHTML);
			$('#wallcommform').slideDown();
		}
})

//Cancel Comment
$('input[name=Cancel]').live('click', function(){
	$('#wallcommform').slideUp(function(){
		$(this).remove();
	});
})

// revealSpan allows text to be hidden with only a small sample visible.
wllWall_class.prototype.revealSpan = function(span) {
	if (span.style.display != 'inline') {
		span.style.display = 'inline';
		btn = document.getElementById('reveal' + span.id);
		btn.innerHTML = '&laquo;&nbsp;less';
	} else {
		span.style.display = 'none';
		btn = document.getElementById('reveal' + span.id);
		btn.innerHTML = '&raquo;&nbsp;more';
	}
}



/*//////////////////////////////////////////////////////////////////////
//                                                                    //
//  onFocus/onBlur functions for comment and wall post fields.        //
//      Provide the ability to add default text to a textarea and     //
//      have that text disappear when the user clicks in the form.    //
//                                                                    //
//////////////////////////////////////////////////////////////////////*/

wllWall_class.prototype.dTextOnBlur = function(field) {
	var wallDefault = 'Ask a question, post a comment or just share your thoughts...';
	var commDefault = 'Respond to this!';
	var custservDefault = 'Ask customer service a question...';
	var value = field.value;
	if ((value == '') || (value == wallDefault) || (value == commDefault) || (value == custservDefault)) {
		var fieldClass = field.getAttribute('class');
		if (fieldClass == 'comment') {
			field.value = commDefault;
		} else if (fieldClass == 'custserv') {
			field.value = custservDefault;
		} else {
			field.value = wallDefault;
		}
		/*(fieldClass == 'comment') ? field.value = commDefault : field.value = wallDefault; */
	}
	field.style.color = '#aaaaaa';
}

wllWall_class.prototype.dTextOnFocus = function(field) {
	var wallDefault = 'Ask a question, post a comment or just share your thoughts...';
	var commDefault = 'Respond to this!';
	var custservDefault = 'Ask customer service a question...';
	var value = field.value;
	if ((value == wallDefault) || (value == commDefault) || (value == custservDefault)) {
		field.value = '';
	}
	field.style.color = '#222222';
}


wllWall_class.prototype.limitText = function(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}


//Check Post
$('#postSubmit').live('click', function() {
	var val = $('#newpost').attr("value");
	// There is either nothing to post or else default text in the form
	if(((val) == '') || (val == 'Ask customer service a question...') || !val) {
		$('#newpost').animate({
			'background-color': '#900',
			 'color': 'white'},
			 500).animate({
				 'background-color': 'white', 
				 'color': '#AAA'}, 
				 500);
	} else {
		$('form[name=wallpostform]').submit();
	}
});

wllWall_class.prototype.checkComment = function(field) {
	var val = field.value;
	// There is either nothing to post or else default text in the form
	if((typeof(val) == 'undefined') || (val == 'Respond to this!test')) {
		Effect.Pulsate(field.id, { pulses:2, duration:1.0 });
	} else {
		document.wallcommform.submit();
	}
}

// Animate news sections: reveal the full article
// revealSpan allows text to be hidden with only a small sample visible.
function revealSpan(span) {
	if (span.style.display != 'inline') {
		span.style.display = 'inline';
		btn = document.getElementById('reveal' + span.id);
		btn.innerHTML = '&laquo;&nbsp;less';
	} else {
		span.style.display = 'none';
		btn = document.getElementById('reveal' + span.id);
		btn.innerHTML = '&raquo;&nbsp;more';
	}
}

/*//////////////////////////////////////////////////////////////////
//                                                                //
// Utility functions: non-object functions for general use:       //
//                                                                //
//////////////////////////////////////////////////////////////////*/

// addEvent: allows for unobtrusive JS.  Can be called to insert functions onto page where required.
if (typeof(addEvent) != 'function') {
	function addEvent(elm, evType, fn, useCapture) {
	    elm["on"+evType]=fn;return;
	}
}

// getUrlVars grabs variables from the GET and returns them as an associative array
if (typeof(getUrlVars) != 'function') {
	function getUrlVars(){
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for(var i = 0; i < hashes.length; i++){
			hash = hashes[i].split('=');
			vars.push(hash[0]);
			vars[hash[0]] = hash[1];
		}
	return vars;
	}
}

// getElementsByClassName: extends and unifies this poorly-implemented function
document.getElementsByClassName = function(clsName){
	var retVal = new Array();
	var elements = document.getElementsByTagName("*");
	for(var i = 0;i < elements.length;i++){
		if(elements[i].className.indexOf(" ") >= 0){
			var classes = elements[i].className.split(" ");
			for(var j = 0;j < classes.length;j++){
				if(classes[j] == clsName)
					retVal.push(elements[i]);
			}
		}
		else if(elements[i].className == clsName)
			retVal.push(elements[i]);
	}
	return retVal;
}



// Bootstrap function to launch a new instance of the Wall Animation class
function wll_wall_anim_bootstrap() {
	wll = new wllWall_class();
/*	var postSubmit = document.getElementById('postSubmit');
	addEvent(postSubmit, 'click', function() { wll.checkPost(document.getElementById('newpost')); });
	var newpost = document.getElementById('newpost');
	addEvent(newpost, 'blur', function() { wll.dTextOnBlur(this); });
	addEvent(newpost, 'focus', function() { wll.dTextOnFocus(this); });
	addEvent(newpost, 'keyup', function() { wll.limitText(this, document.getElementById('countdown'), 500); }); */
}



addEvent(document, 'load', wll_wall_anim_bootstrap());
