var $j = jQuery.noConflict();
var temp;
var custIdBoxTimeout = null;
jQuery.bt.options.closeWhenOthersOpen = true;
var imagesToLoad = [
	'wait.gif',
	'circleX.gif',
	'circleXRollover.gif',
	'productsGetStarted.png',
	'productsGetStartedHover.png',
	'cvv.jpg'
];

var preloadedImages = new Array();

// Header initialization
$j(document).ready(function(){
	// Breakout of frame
	if (top.location != location)
		top.location.href = document.location.href;

	// Forgot password tooltip
	$j('#forgot').bt({
		fill: '#FFF',
		strokeStyle: '#C7C7C7',
		strokeWidth: 4,
		cssStyles: {color: '#808080', fontWeight: 'bold', padding: '0'},
		trigger: 'click',
		spikeLength: 9,
		spikeGirth: 10,
		positions: ['bottom'],
		width: 240,
		contentSelector: "$j('#forgotTooltip').html()"
	});

	// Tabs animation
	$j('.tab, .tabSel').hover(
		function(){
			var ch =  $j(this).find('.listMenu');
			$j(ch).stop(false, true).show(100);
		},
		function(){
			var ch =  $j(this).find('.listMenu');
			$j(ch).stop(false, true).hide(300);
		}
	);

	// Page help tip
	$j('#helpImage').bt({
		contentSelector: "$j('#helpTip')",
		showTip: function(box){
			var $content = $j('.bt-content', box).hide();
			var $canvas = $j('canvas', box).hide();
			var origWidth = $canvas[0].width;
			var origHeight = $canvas[0].height;
			var opacity = 1;

			if ($j.browser.msie)
				opacity = '.9';

			$j(box).show();

			$canvas.css({
				width: origWidth * .5,
				height: origHeight * .5,
				left: origWidth * .25,
				top: origHeight * .25,
				opacity: .1
			}).show()
			.animate({
				width: origWidth,
				height: origHeight,
				left: 0,
				top: 0,
				opacity: opacity
			}, 400, 'easeOutBounce', function(){$content.show()});
		},
		width: 450,
		spikeLength: 15,
		hideOn: 'mouseout',
		closeButton: false,
		spikeGirth: 18,
		strokeStyle: '#DFFFFF',
		strokeWidth: 2,
		fill: 'rgba(20, 60, 85, .9)',
		cssStyles: {color: '#FFF', fontWeight: 'bold'},
		trigger: 'click',
		positions: ['bottom']
	});
});

// Controls initialization
$j(document).ready(function(){
	// Set autoclose for messages
	$j('[id=messageBox]').each(function(){
		var msgBox = $j(this);

		if (msgBox.find('#autoClose').length > 0)
			setTimeout(function(){
				msgBox.fadeOut(1500, function(){
					msgBox.remove();
				})
			}, 5000);
	});

	// Apply lightbox to links
	$j('a[lightbox=true]').lightBox();

	// Preload images
	$j(imagesToLoad).each(function(){
		var image = $j('<img />').attr('src', '/images/' + this);
		preloadedImages.push(image);
	});

	// Set hover for images
	$j('img[hover^=http], img[hover^=/]').live('hover', function(){
		var el = $j(this);

		var src = el.attr('src');
		var hover = el.attr('hover');

		el.attr('src', hover);
		el.attr('hover', src);
	});

	// Set inline label for text inputs
	$j('input[inline_label^=]')
		.inline_label({auto_label: true});
	$j('input[inline_label=]')
		.inline_label({use_title: true});

	// Set tootlip for cust ID boxes
	$j('.custIdBox').each(function(){
		var box = $j(this);

		var content = '<div class="custIdTooltip title">' + box.html() + '</div>'
					+ '<div class="custIdTooltip content">'
					+   box.attr('cName') + '<br />'
					+   box.attr('cCompany') + '<br />'
					+   box.attr('cEmail') + '<br />'
					+   '<div id="autoLogin" title="Quick-login"'
					+   ' class="current blue" onclick="' + box.attr('action') + '">'
					+     '<div class="blue button small">Quick-login</div>'
					+   '</div>'
					+ '</div>';

		box.bt(content, {
			fill: '#004D99',
			strokeStyle: '#116497',
			strokeWidth: 4,
			cssStyles: {color: 'white', fontWeight: 'bold', padding: '0'},
			trigger: ['mouseover', 'click'],
			spikeLength: 9,
			spikeGirth: 10,
			positions: ['bottom']
		});
	}).hover(function(){
		var box = $j(this);

		box.btOff();

		custIdBoxTimeout = setTimeout(function(){
			box.btOn();
		}, 200);
	}, function(){
		clearTimeout(custIdBoxTimeout);
	});

	// Set tootlip for transaction details boxes
	$j('.transactBox').each(function(){
		var box = $j(this);

		var content = '<div class="custIdTooltip title">Additional Details</div>'
					+ '<div class="custIdTooltip content" style="height: 104px;">'
					+   box.find('.content').html()
					+ '</div>';

		box.bt(content, {
			fill: '#004D99',
			strokeStyle: '#116497',
			strokeWidth: 4,
			cssStyles: {color: 'white', fontWeight: 'bold', padding: '0'},
			trigger: ['mouseover', 'click'],
			spikeLength: 9,
			spikeGirth: 10,
			positions: ['left']
		});
	});

	if ($j("#daterange").length > 0) {
		$j("#daterange").daterangepicker({
			arrows: true,
			closeOnSelect: true,
			rangeSplitter: "to",
			prevLinkText: "",
			nextLinkText:"",
			datepickerOptions: {
				changeMonth: true,
				changeYear: true
			}
		});
	}

	$j('.actionSelect').change(function(){
		location.href = $j(this).val();
		$j(this).val('');
	});

	$j('.explainedTooltip').each(function(){
		var cont = $j(this).find('.explainedTooltipCont');

		var name = this.id.split('-');
		name.shift();
		name = name.join('-');

		if (cont.length == 0)
			return;

		$j(this).bt({
			contentSelector: "$j('#tip_cont-" + name + "')",
			fill: cont.attr('bg'),
			strokeStyle: cont.attr('brd'),
			strokeWidth: 3,
			cssStyles: {color: cont.attr('fnt'), fontWeight: 'bold', padding: '0'},
			trigger: ['mouseover', 'click'],
			spikeLength: 15,
			spikeGirth: 10,
			positions: [cont.attr('pos')]
		});

		$j(this).mouseover(function(){
			$j(this).btOff();
			$j(this).btOn();
		});

		$j(this).mouseleave(function(){
			$j(this).btOff();
		});
	});
});

function stripTags(val) {
	val = val.replace(/&(lt|gt);/g, function (strMatch, p1){
		return (p1 == "lt")? "<" : ">";
	});

	var result = val.replace(/<\/?[^>]+(>|$)/g, "");

	result = result.replace(/[\r\n]/g, "");

	return result;
}

function getQueryParams() {
	var query = location.search.substring(1);

	if (!query)
		query = '';

	var vars = query.split("&");
	var params = new Array();

	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		params[pair[0]] = pair[1];
	}

	return params;
}

function buildQuery(params) {
	var queryArr = new Array();

	for (key in params) {
		if (key == undefined || params[key] == undefined)
			continue;

		queryArr.push(escape(key) + '=' + escape(params[key]));
	}

	return queryArr.join('&');
}

function quickLogin() {
	location.href = '/auth/login?' + $j('#quick_login').val();
}

/**
 * Validate the string is an email address.
 */
function checkEmail (strng) {
	var error="";
	if (strng == "") {
		error = "You didn't enter an email address.<br/>";
	}

	var emailFilter=/^.+@.+\..+$/;
	if (!(emailFilter.test(strng))) {
	   error = "Please enter a valid email address.<br/>";
	}
	else {
	   var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
		 if (strng.match(illegalChars)) {
		  error = "The email address contains illegal characters.<br/>";
	   }
	}
	return error;
}

/**
 * Validate the string is a number.
 */
function checkPhone (strng) {
	var error = '';

	var regExp = /(^[0-9\(\)\s\-\+]{10,})$/

	if (!regExp.test(strng))
		error = 'Inavlid phone number.';

	return error;
}

/**
 * Validate the value is a float.
 */
function checkFloat(val, name) {
	var error = "";
	if (val == "") {
		error = name + " is required <br/>";
	}

	var regExp = /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/;
	if (regExp.test(val) == false ) {
		   error = name + " is not in the right format.<br/>";
	}

	return error;
}

/**
 * Validate the string is a valid password.
 */
function checkPassword (strng) {
	var error = "";
	if (strng == "") {
		error = "You didn't enter a password.<br/>";
	}

	var illegalChars = /[\W_]/;
	if ((strng.length < 6) || (strng.length > 8)) {
	   error = "The password is the wrong length.<br/>";
	}
	else if (illegalChars.test(strng)) {
	  error = "The password contains illegal characters.<br/>";
	}
	else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
	   error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.<br/>";
	}
	return error;
}

/**
 * Validate the string is a valid username.
 */
function checkUsername (strng) {
	var error = "";
	if (strng == "") {
		error = "You didn't enter a username.<br/>";
	}

	var illegalChars = /\W/; // allow letters, numbers, and underscores
	if ((strng.length < 4) || (strng.length > 10)) {
	   error = "The username is the wrong length.<br/>";
	}
	else if (illegalChars.test(strng)) {
		error = "The username contains illegal characters.<br/>";
	}
	return error;
}

/**
 * Validate the string is not empty.
 */
function isEmpty(strng, elementName) {
	var error = "";
	if (strng.length == 0) {
		error = elementName + " is required.<br/>";
	}
	return error;
}

function sendWidgetMessage()
{
	var mes = $j("#representative_box_message");

	if (mes.val().length == 0)
		return;

	$j.overlay.show("#representative_box_table");

	$j.ajax({
		type: "POST",
		url: "/ajax/Ticketing",
		dataType: "text",
		data: {
			to: mes.attr('to'),
			from: mes.attr('from'),
			products: eval(mes.attr('products')),
			subject: 'Question',
			message: mes.val()
		},
		success: function(res){
			$j.overlay.show("#representative_box_table", false);

			if (res == 1) {
				$j("#representative_box_submit_row").hide();
				$j("#representative_box_message_row").hide();

				$j("#representative_box_message_ok").show();
			} else {
				$j("#representative_box_message_error").show();

				setTimeout(function(){
					$j("#representative_box_message_error").fadeOut(1500);
				}, 5000);
			}
		}
	});
}

