POP.UTILS.getUrlHash = function () {
	var vars = [],
		hash,
		hashes = '';
	if (window.location.hash) {
		hashes = window.location.hash.replace('#', '').split('&');
	}
	for (var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

POP.UTILS.getUrlQueryString = function () {
	var vars = [],
		hash,
		hashes = '';
	hashes = window.location.href.split('?')[1].split('#')[0].split('&');
	for (var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
}

//UTILITY FUNCTIONS
function print_r(arr, level) {
	var dumped_text = "";
	if (!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for (var j = 0; j < level + 1; 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,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += print_r(value, level + 1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>" + arr + "<===(" + typeof (arr) + ")";
	}
	return dumped_text;
}

//Logs a bit more info... DO NOT LOG huge objects ex: jQuery Objects
function log(info, label) {
   return; //if not debugging just return
	if (label === undefined) {
		label = '';
	} else {
		label += ': ';
	}
	console.log('==========================');
	if (typeof info === 'object') {
		console.log(label + '' + print_r(info));
	} else {
		console.log(label + '' + info);
	}
	console.log('==========================');
}

function unixToHumanTime(unix) {
	var timeObj = {},
		t, d;
	d = new Date(Number(unix) * 1000);
	timeObj.date = d.toLocaleDateString();
	t = d.toLocaleTimeString();
	timeObj.time = t.replace(/[0-9]{1,2}(:[0-9]{2}){2}/, function (time) {
		time = time.replace(/.{3}$/, '');
		var hms = time.split(':'),
			h = +hms[0],
			suffix = (h < 12) ? 'AM' : 'PM';
		hms[0] = h % 12 || 12;
		return hms.join(':') + suffix
	});
	return timeObj;
}


//END UTILITY FUNCTIONS


//PLUGINS, ETC
//HoverIntent

(function ($) { $.fn.hoverIntent = function (f, g) { var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; cfg = $.extend(cfg, g ? { over: f, out: g} : f); var cX, cY, pX, pY; var track = function (ev) { cX = ev.pageX; cY = ev.pageY }; var compare = function (ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) { $(ob).unbind("mousemove", track); ob.hoverIntent_s = 1; return cfg.over.apply(ob, [ev]) } else { pX = cX; pY = cY; ob.hoverIntent_t = setTimeout(function () { compare(ev, ob) }, cfg.interval) } }; var delay = function (ev, ob) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); ob.hoverIntent_s = 0; return cfg.out.apply(ob, [ev]) }; var handleHover = function (e) { var ev = jQuery.extend({}, e); var ob = this; if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t) } if (e.type == "mouseenter") { pX = ev.pageX; pY = ev.pageY; $(ob).bind("mousemove", track); if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout(function () { compare(ev, ob) }, cfg.interval) } } else { $(ob).unbind("mousemove", track); if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout(function () { delay(ev, ob) }, cfg.timeout) } } }; return this.bind('mouseenter', handleHover).bind('mouseleave', handleHover) } })(jQuery);


//Misc POP

POP.rerunCufon = function () {
	Cufon.replace('h1, h2, h3');
	Cufon.replace('a.block-btn');
};

// start TextareaMaxlength

/**
*	Enforces maxlength in textarea
**/
POP.TextareaMaxlength = function ($textarea) {
	var self = this;
	this.textarea = $textarea;
	if (this.textarea.length === 0) {return;}
	this.maxlength = this.textarea.attr('maxlength');
	this.textarea.bind('keyup', function (e) {
		self.enforce();
	});
};
POP.TextareaMaxlength.prototype = {
	enforce: function(){
		var self = this;
		if (this.textarea.val().length >= this.maxlength) {
			self.textarea.val(self.textarea.val().substring(0, self.maxlength));
		}
	}
};

/**
*	Displays/ hides loading gif
**/
POP.loadingMsg = function (element, config, str) {
    var self = this;
    self.config = $.extend({
		top: null,
		left: null,
		fadeInTime: 200,
		fadeOutTime: 200,
		loadingImageLight: '/_ui/img/global/spinner.gif',
		loadingImageDark: '/_ui/img/global/spinner.gif'
	}, config || {});
	
    self.__init(element, str);
};

POP.loadingMsg.prototype = {
	__init: function(element, str) {
        var self = this,
			top = self.config.top, 
			left = self.config.left;
			
		self.lWidth = 32;
		self.lHeight = 32;
        self.parentEl = $(element);
		if(str === 'light') {
			self.loadingEl = $('<img src="'+ self.config.loadingImageLight +'" style="display:none" />');    
		}else {
			self.loadingEl = $('<img src="'+ self.config.loadingImageDark +'" style="display:none" />');    
		}
        self.parentEl.append(self.loadingEl);
        self.pHeight = self.parentEl.height();
        self.pWidth = self.parentEl.outerWidth(true);

        if(top === null) {
            top = Number(self.pHeight / 2 - self.lHeight / 2) + 'px';
        }
        if(left === null) {
            left = Number(self.pWidth / 2 - self.lWidth / 2) + 'px';
        }
         
        self.loadingEl.hide();
        self.parentEl.css({
            'position': 'relative'
        });
        self.loadingEl.css({
            'left': left,
            'position': 'absolute',
            'top': top
        });
    },
	
	show: function() {
		var self = this;
		self.loadingEl.fadeIn(self.config.fadeInTime);
	},
	
	hide: function() {
		var self = this;
		self.loadingEl.fadeOut(self.config.fadeInTime, function() {
            self.loadingEl.remove();
        });
	}
};
  
/**
*	Replace Submit Buttons for styling
**/

POP.replaceSubmit = (function () {

	var submits = [];

	function __init() {}

	function __replace(element) {
		var el = element || 'body',
			submits = $(el).find('input[type=submit]').not('.search-field input, .HiddenButton, .hide-if-js');
		submits.css({
			'left': '-999999px',
			'position': 'absolute',
			'top': '-999999px'
		});
		submits.each(function (i, val) {
			var submit = $(this),
				text = submit.val(),
				btn = [], disabled;
			(submit.hasClass('disabled')) ? disabled = 'disabled' : disabled = '';
			btn = $('<a href="#" class="block-btn '+ disabled +'">' + text + '</a>');

			btn.insertBefore(submit);
			btn.bind('click', function (e) {
				e.preventDefault();
				if(!btn.hasClass('disabled')) {
					submit.click();
				}
			});
		});
	}

	return {
		replace: function (element) {
			__replace(element);
		}
	}

} ());

/**
*	Toggle between show 'more' / 'less' - 2 DIFFERENT text areas
**/
POP.showMore = function (targets, options) {

	var self = this,
		els = $(targets),
		config = $.extend({
			btnTextMore: 'Show More',
			btnTextLess: 'Show Less'
		}, options || {});

	for (var i = 0, len = els.length; i < len; i++) {
		__init($(els[i]));
	}

	function __init(obj) {
		__addEventListeners(obj);
	}

	function __addEventListeners(obj) {
		var isHidden = obj.find('.isHidden'),
			isShown = obj.find('.isShown'),
			toggleBtn = obj.find('.btn-show-more');

		if (isHidden.length === 0) {isHidden = false}
		if (isShown.length === 0) {isShown = false}
		if (toggleBtn.length === 0) {toggleBtn = false}

		if (isHidden && isShown && toggleBtn) {
			toggleBtn.bind('click', function (e) {
				e.preventDefault();
				__onToggleBtnClick(obj, toggleBtn);
			});
			toggleBtn.html(config.btnTextMore);
		} else if (isHidden && !isShown) {
			isHidden.removeClass('isHidden');
		}

	}

	function __onToggleBtnClick(obj, btn) {
		var isHidden = obj.find('.isHidden'),
			isShown = obj.find('.isShown'),
			btnText = btn.text();

		isShown.hide(200, function () {
			$(this).toggleClass('isShown').toggleClass('isHidden');
		});
		isHidden.show(200, function () {
			$(this).toggleClass('isHidden').toggleClass('isShown');
		});
		(btnText == config.btnTextMore) ? btn.html(config.btnTextLess) : btn.html(config.btnTextMore);
	}
}

/**
*	Search Input - toggles the text
**/
POP.ToggleInputText = function (target, options) {
	var el = $(target),
		config = $.extend({
			defaultText: 'Search'
		}, options || {}),
		text = '';

	__init();

	function __init() {
        
		var i = document.createElement('input');
		if('placeholder' in i) {
			return;
		}

		text = el.val();
		if (!text) {
			text = config.defaultText;
			el.val(text);
		}
		__addEventListeners();
	}

	function __addEventListeners() {
		el.focusin(function (e) {
			el.val(' ');
		});
		el.focusout(function (e) {
			el.val(text);
		});
	}
}

/**
*   Facebook share links
**/
POP.FacebookShareLinks = function (targets) {

	var self = this,
		els = $(targets);

	__init();

	function __init() {
		__addEventListeners();
	}

	function __addEventListeners() {
		els.live('click', function (e) {
			e.preventDefault();
			__onFacebookShareClick(e);
		});
	}

	function __onFacebookShareClick(e) {
		var link = $(e.currentTarget),
			query = link.attr('href');
		_gaq.push([
			'_trackEvent', 'Social Share', 'Facebook', window.location.href
		]);
		window.open(
			query,
			'sharer',
			'toolbar=0,status=0,width=626,height=436'
		);
	}
};

/**
*   Twitter share links
**/
POP.TwitterShareLinks = function (targets) {

	var self = this,
		els = $(targets);

	__init();

	function __init() {
		__addEventListeners();
	}

	function __addEventListeners() {
		els.live('click', function (e) {
			e.preventDefault();
			__onTwitterShareClick(e);
		});
	}

	function __onTwitterShareClick(e) {
		var link = $(e.currentTarget),
			query = link.attr('href');
		_gaq.push([
			'_trackEvent', 'Social Share', 'Twitter', window.location.href
		]);
		window.open(
			query,
			'targetWindow',
			'toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=550,height=450'
		);
	}
};

/**
*	Donation Widget GA Tracking
**/
POP.DonationGA = function () {
	var self = this;
	this.fsDonation = $('#donation-widget');
	if (this.fsDonation.length == 0) {return;}
	this.txtInput = this.fsDonation.find('.text-xshort');
	this.submitLink = this.fsDonation.find('.submit-lnk');
	this.kenticoName = this.fsDonation.find('.kentico-name').val();
	this.kenticoID = this.fsDonation.find('.kentico-id').val();
	this.val = this.txtInput.val();
	if (this.val.substr(0,1) == '$') {
		this.val = this.val.substr(1);
	}
	this.val = Math.round(parseFloat(this.val));
	this.url = window.location.pathname;
	this.title = document.title;

	this.submitLink.click(function (e) {
		//e.preventDefault();
		self.__trackEvent();
	});

};
POP.DonationGA.prototype = {
	__trackEvent: function () {
		var self = this;
		var category = String('Support ' + this.title + ' ' + this.kenticoName + ' ' + this.kenticoID);
		var newVal = this.txtInput.val();
		if (newVal.substr(0,1) == '$') {
			newVal = newVal.substr(1);
		}
		var value = Number(Math.round(parseFloat(newVal)));
		var action = escape(this.val);
		var label = escape(this.url);
		
		//console.log(category, action, label, value);
		_gaq.push([
			'_trackEvent',
			category,
			action,
			label,
			value
		]);
	}
};

/**
*	Attach click events for GA
**/
POP.attachGlobalTracking = (function() {
	var _self = {},
		_pageUrl = '';
	return {
		init: function(targets) {
			_self = POP.attachGlobalTracking;
			_pageUrl = window.location.pathname;
			var targetsLen = targets.length;
			for(var i = 0; i < targetsLen; i++) {
				_self.addEventListeners(targets[i]);
			}
		},
		addEventListeners: function(targetObj) {
			$(window).delegate(targetObj.selector, 'click', function(e) {
				//console.log('category: ', targetObj.category, ' url: ', _pageUrl, ' label: ', targetObj.label);
				_gaq.push([
					'_trackEvent',
					targetObj.category,
					_pageUrl,
					targetObj.label
				]);
			});
		}
	}
})();



