/**
 * uses the hardened javascript pattern from
 * http://kentbrewster.com/case-hardened-javascript
 **/

(function () {
	var trueName = '';
	for (var i = 0; i < 16; i++) {
		trueName += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
	}
	window[trueName] = {};
	var $ = window[trueName];
	$.f = function () {
		return {
			init: function (target) {
				var scripts = document.getElementsByTagName('script');
				for (var i = 0; i < scripts.length; i++) {

					if (scripts[i].src.match(target)) {

						if (scripts[i].innerHTML) {
							if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]+$/.test(scripts[i].innerHTML.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) {
								try {
									$.a = eval( '(' + scripts[i].innerHTML + ')' );
								}
								catch(err) { }
							}
						}
						if (typeof $.a !== 'object') {
							$.a = {};
						}
						$.w = document.createElement('div');

						/************************************
						 * Begin Code
						 */
						var randomString = function(length) {
							var chars =	'0123456789'
								    	+ 'ABCDEFGHIJKLMNOPQRSTUVWXTZ'
								    	+ 'abcdefghiklmnopqrstuvwxyz';
						
							var random = '';
							for (var i = 0; i < length; i++) {
								var rnum = Math.floor(Math.random() * chars.length);
								random += chars.substring(rnum, rnum + 1);
							}
						
							return random;
						};
						
						var cookie = function(name, value, options) {
						    if (typeof value != 'undefined') { // name and value given, set cookie
						        options = options || {};
						        if (value === null) {
						            value = '';
						            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
						            options.expires = -1;
						        }
						        var expires = '';
						        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
						            var date;
						            if (typeof options.expires == 'number') {
						                date = new Date();
						                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
						            } else {
						                date = options.expires;
						            }
						            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
						        }
						        // NOTE Needed to parenthesize options.path and options.domain
						        // in the following expressions, otherwise they evaluate to undefined
						        // in the packed version for some reason...
						        var path = options.path ? '; path=' + (options.path) : '';
						        var domain = options.domain ? '; domain=' + (options.domain) : '';
						        var secure = options.secure ? '; secure' : '';
						        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
						    } else { // only name given, get cookie
						        var cookieValue = null;
						        if (document.cookie && document.cookie != '') {
						            var cookies = document.cookie.split(';');
						            for (var i = 0; i < cookies.length; i++) {
						                var cookie = jQuery.trim(cookies[i]);
						                // Does this cookie string begin with the name we want?
						                if (cookie.substring(0, name.length + 1) == (name + '=')) {
						                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
						                    break;
						                }
						            }
						        }
						        return cookieValue;
						    }
						};

						
						var useSessionHack = jQuery.browser.msie;
						var sessionKey = null;

						if (useSessionHack) {
							sessionKey = cookie('chideit_session');
						}

						var displayResults = function (result, div, fade) {
							div.text('');
							var container = jQuery('<div><\/div>').hide().appendTo(div);
							var list = jQuery('<ul class="results"><\/ul>').appendTo(container);
						
							if (result.results) {
								jQuery.each(result.results, function(index){
									var percentage;
									var count;
									if (result.total === undefined) {
										percentage = this[1];
										count = '';
									}
									else {
										if (result.total == 0) {
											percentage = 0;
										} else {
											percentage = Math.round(this[1] / result.total * 100);
										}
										count = ' (' + this[1] + ' votes)';
									}
									jQuery('<li><div><strong>' + this[0] + '</strong> - ' + percentage + '%' + count + '<\/div><div class="bar">&nbsp;<\/div><\/li>').appendTo(list).data('percentage', percentage);
								});
							}
						
							if (result.total !== undefined) {
								container
									.append('<strong>Total Votes<\/strong> - ' + result.total);
							}
						
							if (result.has_voted) {
								container.append(' <br\/>Thank you for voting!');
							}
						
							if (result.can_vote && !result.has_voted) {
								container
									.append('<div><a href="#" class="poll">Back to Poll<\/a></div>')
									.find('a.poll')
										.click(function (e) {
											e.preventDefault();
											container.fadeOut('slow', function () {
												container.remove();
												displayPoll(result, div, true);
											});
										});
							}
						
							var animateBars = function () {
								container.find('div.bar').each(function () {
									jQuery(this).css({
										width: '0%'
									}).animate({
										width: jQuery(this).parent().data('percentage') + '%'
									});
								});
							};
						
							if (fade) {
								container.fadeIn('slow', animateBars);
							} else {
								container.show();
								animateBars();
							}
							if ($.a.style !== undefined) {
								for (key in $.a.style) {
									jQuery(key).css($.a.style[key]);
								}
							}
						};
						
						var displayPoll = function (info, div, fade) {
							var form = jQuery('<form method="post" action="' + $.a.url + '"></form>').hide();
							var choices = jQuery('<ul class="choices"><\/ul>').appendTo(form);
							jQuery.each(info.choices, function (index) {
								choices.append('<li><label for="poll-choice-' + index + '"><input type="radio" name="choice" title="'+this+'" alt="'+this+'" id="poll-choice-' + index + '" value="' + index + '"> ' + this + '<\/label><\/li>');
							});
							form
								.append('<input type="submit" title="Submit Your Selection" alt="Submit Your Selection" value="Vote">');
						
							if (info.results !== undefined) {
								form
									.append('<a href="#" title="View the current results of this poll" title="View the current results of this poll" class="results">View Poll Results<\/a>');
							}
							form.append('<br/><small>Powered by <a href="http://www.fluidsurveys.com" title="FluidSurveys - Best Online Survey Software on the Web!" alt="FluidSurveys - Best Online Survey Software on the Web!">FluidSurveys.com</a></small>')
							form
								.find('a.results')
									.click(function (e) {
										e.preventDefault();
										form.fadeOut('slow', function () {
											form.remove();
											displayResults(info, div, true);
										});
									});
							form.submit(function (e) {
								e.preventDefault();
								var data = {
									choice: form.find('input[name="choice"]:checked').val(),
									c: randomString(40)
								};
								if (useSessionHack && sessionKey) {
									data.session = sessionKey;
								}
								jQuery.get($.a.url, data, function (result) {
									if (result.success === false) {
										return;
									}
									form.fadeOut('slow', function () {
										form.remove();
										displayResults(result, div, true);
									});
								}, 'jsonp');
							});
						
							form.appendTo(div);
						
							if (fade) {
								form.fadeIn('slow');
							} else {
								form.show();
							}
							if ($.a.style !== undefined) {
								for (key in $.a.style) {
									jQuery(key).css($.a.style[key]);
								}
							}
						};
						var data = { c: randomString(40) };
						if (useSessionHack && sessionKey)
							data.session = sessionKey;
						jQuery.get($.a.url, data, function (result) {
							var poll = jQuery($.w);
							var div = jQuery('<div><\/div>');
							if (useSessionHack && result.session) {
								sessionKey = result.session;
								cookie('chideit_session', sessionKey, { expires: 365 });
							}
							poll
								.text('')
								//.append('<div class="header">Poll<\/div>')
								.append('<div class="question">' + result.question + '<\/div>')
								.append(div)
								.attr('id', 'poll');
							
							if (!result.can_vote || result.has_voted) {
								displayResults(result, div);
							} else {
								displayPoll(result, div);
							}
							if ($.a.style !== undefined) {
								for (key in $.a.style) {
									jQuery(key).css($.a.style[key]);
								}
							}
						}, 'jsonp');
						
						/**
						 * End Code
						 ************************************/

						scripts[i].parentNode.insertBefore($.w, scripts[i]);
						scripts[i].parentNode.removeChild(scripts[i]);
						break;
					}
				}
			}
		};
	}();

	/** CONFIGURE THE REGEX FOR THIS SCRIPT'S URL **/

	var thisScript = /(^https?:\/\/[^\/]*(\:\d+)?)?\/.*js\/polls\/embed\.js/;
	if (typeof window.addEventListener !== 'undefined') {
		window.addEventListener('load', function() { $.f.init(thisScript); }, false);
	} else if(typeof window.attachEvent !== 'undefined') {
		window.attachEvent('onload', function() { $.f.init(thisScript); });
	}
})();
