
//    cms/templates/common/utils.js

	function showPopUp(id, btnOfsLft, btnOfsTop) {
		bt_log_line('pop_up', id);

		btnOfsLft = btnOfsLft || 0;
		btnOfsTop = btnOfsTop || 0;
		closeAll();
		var $id = $('#' + id);
		var w  = $id.width();
		var h  = $id.height();
		var ww = $(window).width();
		var wh = $(window).height();
		$id.css({left:(ww-w)/2, top:(wh-h)/4});
		var $btn = $('#' + id + ' .close-btn');
		$btn.css({left:(ww-w)/2 + w - btnOfsLft, top:(wh-h)/4 + btnOfsTop});
		$("#full-screen-gray,#" + id).show();
	}

	function signOut() {
		closeAll();
		jQuery.get('/index.php?ACT=10', function(){
			window.location.reload(true);
			return false;
		});
	}

	$.easing.btEase = function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	}

// --------------------------------------- srchTextToUrl -------------------------------------------

	function srchTextToUrl(srchText) {
		srchText = $.trim(srchText).replace('&nbsp;', '').replace('/', '~').replace('&', '$')
								   .replace('+', '^').replace(/\s+/g, '+').replace(/[^a-z0-9~$^+]/i, '');
		return '/all/ss' + (srchText ? '/' + srchText : '');
	}

// --------------------------------------- COOKIE FUNCS --------------------------------------------

	function setCookie(name, value, days, hoursIn) {
		var expires;
		var hours = ((days || 0) * 24) + (hoursIn || 0);
		if (hours) {
			var date = new Date();
			date.setTime(date.getTime()+(hours*60*60*1000));
			expires = "; expires="+date.toGMTString();
		}
		else expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}

	function cookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}

	function eraseCookie(name) {
		setCookie(name,"",-1);
	}

// --------------------------------------- ucwords -------------------------------------------------

	function ucwords(str) {
		return (str + '').toLowerCase().replace(/^(.)|\s(.)/g,
			function ($1) {
				return $1.toUpperCase();
			});
	}


// --------------------------------------- print_r --------------------------------------

	function print_r(arr, level) {
		var txt = "";
		level = level || 0;
		var level_padding = "";
		for(var j = 0; j <= level; j++)
			level_padding += "  ";
		if(typeof(arr) == 'object') { //Array/Hashes/Objects
			for(var item in arr) {
				var value = arr[item];
				if(typeof(value) == 'object') { //If it is an array,
					txt += level_padding + item + " ...\n";
					txt += print_r(value, level+1);
				} else {
					txt += level_padding + item + " => " + value + "\n";
				}
			}
		} else { //Stings/Chars/Numbers etc.
			txt = typeof(arr) + ': ' + arr;
		}
		return txt;
	}

// --------------------------------------- bt_log_line --------------------------------------
	function bt_log_line(action, msg, obj) {
		var objstr = null;
		if(obj)
			objstr = print_r(obj);
		$.ajax({
			type: 'POST',
			url: '/includes/php/logging-ajax.php',
			data: {action:action, msg:msg, obj:objstr}
		});
	}

// --------------------------------------- submitFormWithAjax --------------------------------------

	function submitFormWithAjax($form, url, reqData, callback, noAlert) {
		url = url || $form.attr('action');
		reqData = reqData || {};
		var method = $form.attr('method') || 'POST';
		var formOK = true;
		$form.find('input,textarea').each(function() {
			var attrName = $(this).attr('name');
			var val = $(this).val();
			if(attrName == 'screen_name' && !val) {
				alert('Your screen name is required.  Please use your full name.');
				formOK = false;
				bt_log_line('err_sub_form_aja', 'screen name missing');
			}
			if(!($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio')
				|| $(this).attr('checked'))
				reqData[attrName] = val;
		});
		$form.find('select').each(function() {
			var attrName = $(this).attr('name');
			reqData[attrName] = $(this).find('[selected]').text();
			return true;
		});
		bt_log_line('sub_form_ajax', url, reqData);
		if(formOK) {
			$.ajax({
				type: method,
				url: url,
				data: reqData,
				dataType: 'json',
				success: function(data) {
					if((callback && noAlert) || data.status == 'ok')
						callback && callback(data);
					else if(data.val !== undefined) {
						var msgs = data.val[1];
						var msg = '';
						for(var i=0; i < msgs.length; i++)
							if(msgs[i].indexOf('username') == -1 ||
									(msgs[i].indexOf('must submit') == -1
										&& msgs[i].indexOf('available') == -1))
								msg += msgs[i].replace(/&nbsp;/i, ' ')
											  .replace(/username/i, 'email address') + '\n';
						alert(msg);
					} else if(data.msg !== undefined) {
						alert(data.msg);
					} else
						alert(data.status);
				}
			});
		}
	}

// ----------------------------------- closeAll -----------------------------------
	closeAllList = [];
	function closeAll() {
		bt_log_line('closeAll');
		for(var i=0; i < closeAllList.length; i++)
			closeAllList[i]();
		$(".close-all").hide();
		return false;
	}

// ----------------------------------- callHome -----------------------------------
	function callHome() {
		var number = $('#call-home').val();
		if(number == '123-456-7890') {
			alert('Please enter your phone number before calling.');
			return false;
		}
		if(!number.match(/[^\d]*(\d\d\d)[^\d]*(\d\d\d)[^\d]*(\d\d\d\d)[^\d]*/)) {
			alert('Bad number format.  \nIt should look like: 123-456-7890.');
			return false;
		}
		$.getJSON('/cms/templates/common/google-voice-ajax.php',
			{number: number, name:"btq.in"},
			function(json) {
				if(json.status != 'ok=true')
					alert('Error connecting to Google Voice: ' + json.status);
			});
		alert('Your phone will ring momentarily.');
		return false;
	}

// ----------------------------------- pop-ups -----------------------------------
	function showShipping() {
		showPopUp('shipping-info');
		return false;
	}
	function showPhone() {
		showPopUp('phone-popup'); 
		return false;
	}

// ------------------------------------ INIT ------------------------------------------

	$(function() {
		$('.go-back').live('click', function(){
			history.go(-1);
			return false;
		});
		$("a").live('click', function(){
			if(bt_debug)
				return;
			var href = $(this).attr('href');
			console.log(href);
			if(href && (!(href == '#' ||
						  href.charAt(0) == '/' || 
						  href.indexOf('dsq') != -1 || 
						  href.indexOf('disqus') != -1 || 
					      href.match(/^(https?:\/\/)?(www.)?((p\.)?btq\.in|boutiquing\.com)/i)))) {
				bt_log_line('click_exit', href);
				window.open(href);
				return false;
			}
		});

		$(".greyed-out").click(closeAll);
		$(".close-all-btn").live('click', closeAll);

		$('.ship-info').click(showShipping).css({cursor:'pointer', 'text-decoration':'underline'});
		$('.phone-popup').click(showPhone).css({cursor:'pointer', 'text-decoration':'underline'});

		$("#site-search-input")
			.focus(function(){
				var val = $(this).val();
				if(val == ' search website')
					$(this).val('');
			})
			.blur(function() {
				$(this).val(' search website');
			})
			.keydown(function(e){
				if (e.keyCode == 9 || e.keyCode == 13) {
					var val = $.trim($(this).val());
					if(val) {
						window.location = '/' + btRegionCode + '/int/site_search_' + escape(val);
						return false;
					}
				}
			});
			
		$("#enter-email")
			.focus(function(){
				var $this = $(this);
				var val = $this.val();
				if(val == 'enter email address') {
					val = $this.val('');
					 $(this).css('color', 'black');
				}
			})
			.blur(function() {
				$(this).css('color', 'gray');
				$(this).val('enter email address');
				return false;
			})
			.keydown(function(e){
				if (e.keyCode == 9 || e.keyCode == 13) {
					var $this = $(this);
					var val = $.trim($this.val());
					if(val) {
						if(! /^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i.test(val))
							alert('Please enter a valid email address.');
						else {
							gaPage('email-list-signup');
							$.getJSON('/cms/templates/common/ajax_email.php', {email:val}, function(){
								alert('The email address ' + val + '\n'
									+ 'has been added to the boutiquing.com mailing list.')
							});
						}
					} else {
						$this.css('color', 'gray');
						$this.val('enter email address');
					}
					return false;
				}
			});
		$('#call-btn').click(callHome);
		$('#call-home')
			.click(function() {
				if($(this).val() == '123-456-7890')
					$(this).val('');
			})
			.keydown(function(e){
				if (e.keyCode == 9 || e.keyCode == 13){
					callHome();
					return false;
				}
			});
	});
