/**
* In case of problems contact feedback@getyourpoll.com
*/
function Poll() {
        var questions = null;
	var results = null;
        var style = "";
        var poll_question = "";
        var poll_id = 0;
        var questions_hash = {};
        var can_vote = 1;
        var pollAnswer = null;

	this.getQuestion = function(id) {
		for (var i=0; i<questions.length; i++) {
			var question = questions[i];
			if (question != undefined && question['id'] == id) {
				return question;
			}
		}
		return undefined;
	};

	this.setQuestion = function(id, updated_question) {
		var new_questions = new Array();
		for (var i=0, j=0; i<questions.length; i++) {
			if (questions[i] == undefined) continue;
			if (questions[i]['id'] == id) {
				if (updated_question != undefined) {
					new_questions[j++] = updated_question;
				}
			} else {
				new_questions[j++] = questions[i];
			}
		}
		questions = new_questions;
	};


	this.addQuestion = function() {
		var qid = 0;
		for (var i=0; i<questions.length; i++) {
			if (questions[i] == undefined) continue;
			qid = (questions[i]['id'] > qid) ? questions[i]['id'] : qid;
		}
		questions[questions.length] = {'id' : qid+1, 'options' : [], 'question' : 'New question', 'ftype' : 1, 'poll_id' : 43};
		this.setQuestions(questions);
	};

	this.onload = function() {
	};

	this.getQuestions = function() {
		return questions;
	};

        this.setQuestions = function(q) {
                questions = q;
		can_vote = 1;
		if (q.length == 0) {
			this.showResultsTable();
		}
                this.process();
                ph = document.getElementById('hiddenpoll');
                if (ph != undefined) {
                        ph.style.visibility = 'visible';
                }

		if (typeof cssBody == 'string' && cssBody.length > 0) {
			var s = document.createElement('style');
			s.setAttribute("type", "text/css");
			if(s.styleSheet){// IE
				s.styleSheet.cssText = cssBody;
			} else {// w3c
				var cssText = document.createTextNode(cssBody);
				s.appendChild(cssText);
			}
			if (document.body) {
				document.body.appendChild(s);
			} else if (document.getElementsByTagName('head')[0]) {
				document.getElementsByTagName('head')[0].appendChild(s);
			}
		}
		this.onload();
        };

        this.setResults = function(r) {
                results = r;
                can_vote = 0;
                this.process();
        };

        this.loadQuestions = function() {
                var pars = "";
                if (typeof client_uid != 'undefined') {
                        pars += "&client_uid=" + client_uid;
                }
                if (typeof survey_id != 'undefined') {
                        pars += "&survey_id=" + survey_id;
                }
		var backurl = escape(document.referrer);
                var refurl = escape(document.location.href);
		pars += '&backurl=' + backurl + '&refurl=' + refurl;
		var url = "http://www.getyourpoll.com/gypoll/poll_data.js?a=b" + pars;
                this.doLoad(url);
        };

        this.prepareSpan = function(span, url) {
                        var s = span.getElementsByTagName("script")[0];
                        if (s.setAttribute) {
                                s.setAttribute('src', url); 
                                s.setAttribute('id', 'jsspan'); 
                                s.setAttribute('language', "JavaScript"); 
                        } else {
                                s.src = url;
                                s.id = 'jsspan';
                                s.language = "JavaScript";
                        }
        };

        this.doLoad = function(url) {
                var _span = document.createElement("span");
                var span = document.body.appendChild(_span);
                span.style.display = 'none';
                span.innerHTML = 's<s'+'cript></' + 'script>';
                this.prepareSpan(span, url);
        };


        this.errorMsg = function(message) {
                document.getElementById('gyp_span_message').style.display = '';
                document.getElementById('gyp_span_message').style.color = 'red';
                document.getElementById('gyp_span_message').innerHTML = message;
                return false;
        }

        this.formSubmit = function(form) {
                var poll_answer = null;
                var req = {};
		var voted = {};
                for(var i=0;i < form.elements.length; i++) {
                        var pos = form.elements[i].name.indexOf("answer-");
                        if (pos == 0) {
                                var question_id = form.elements[i].name.substring(7);
                                var ftype = questions_hash[question_id]['ftype'];
                                var value = form.elements[i].value;
                                poll_id = questions_hash[question_id]['poll_id'];
                                if (ftype == 3 && value.length > 0 && parseInt(value) != value) {
                                        this.errorMsg("Please fill the question " + questions_hash[question_id]['question'] + " with numeric, 99 for example");
                                        return false;
                                } else if (value.length == 0) {
                                        this.errorMsg("Please fill the question: " + questions_hash[question_id]['question']);
                                        return false;
                                } else if (value.length > 0 && ftype == 4) {
                                        req[(((ftype == 3) ? "t" : "v") + question_id)] = value;
					if (voted[question_id] == undefined) {
						voted[question_id] = new Array();
					}
					voted[question_id][0] = value;
                                } else if (value.length > 0 && (ftype == 1 || ftype == 2) && form.elements[i].checked) {
                                        req[("v" + question_id + "--" + i)] = value;
					if (voted[question_id] == undefined) {
						voted[question_id] = new Array();
					}
					voted[question_id][i] = value;
                                }
                        }
                }
                var c = 0;
                var str = "";
                for (param in req) {
                        var name = param;
                        str += "q" + name + "=" + escape(req[param]) + "&";
                        c++;
                }
                str = str.substring(0, str.length - 1);
                var qc = 0;
                for (var i= 0; i<questions.length; i++) {
                        if (typeof questions[i] == 'undefined') continue;
                        qc++;
                }
                if (c < qc) {
                        return this.errorMsg('No one selected');
                }
                pollAnswer = str;
                try {
                        backurl = escape(document.referrer);
                        refurl = escape(document.location.href);

                        var req = 'http://www.getyourpoll.com/gypoll/poll_submit.js?poll_id=' + poll_id + '&' + str + '&backurl=' + backurl + '&refurl=' + refurl;
			this.postAnswer(req, voted);
                        document.getElementById('gyp_span_message').style.display = '';
                        document.getElementById('gyp_span_message').style.color = 'green';
                        document.getElementById('gyp_span_message').innerHTML = "Your vote submitted. Thanks!";
                } catch (e) {
                        document.getElementById('gyp_span_message').style.display = '';
                        document.getElementById('gyp_span_message').style.color = 'red';
                        document.getElementById('gyp_span_message').innerHTML = e;
                }
		if (typeof urchinTracker != 'undefined') {
			urchinTracker('/gyvoted');
		}
                return false;
        };


	this.postAnswer = function(req, voted) {
		this.doLoad(req);
	};

        this.drawPollTable = function(style) {
                var poll_answer = "";
                if (typeof poll_submit_text != 'string') {
                        poll_submit_text = "Vote";
                }
                var poll_url = 'http://www.getyourpoll.com/gypoll/poll_submit.js';

                var aid = 0;
                var poll_votes = {};

                var ret = '';
                ret += '<form id="pollForm" action="' + poll_url + '" onSubmit="javascript: return formSubmit(this)">';
                ret += '<table border="0" id="gyp_polltable" class="gyp_polltable" style="' + style + '" width="100%">';
                var vert = true;
                if (questions.length >= 1) {
                        for (var i=0; i<questions.length; i++) {
                                var question = questions[i];
                                if (typeof question == 'undefined') continue;
                                poll_question = question['question'];
                                retAr = this.getOptions(question);
                                ret += '<tr><td class="gyp_td_question" colspan="' + retAr.length + '"><span class="gyp_span_question">' + poll_question + '</span></td></tr>';
                                for (var t=0; t<retAr.length; t++) {
                                        if (vert == true || t == 0) {
                                                ret += '<tr>';
                                        }
                                        ret += '<td class="gyp_td_answer">';
                                        ret += retAr[t];
                                        ret += '</td>';
                                        if (vert == true || t == retAr.length-1) {
                                                ret += '</tr>';
                                        }

                                }

                        }
                }
                ret += '<tr><td class="gyp_td_submit" colspan="' + retAr.length + '"><input class="gyp_submit" type="submit" value="' + poll_submit_text + '" /></td></tr>';
                ret += '</table>';
                ret += '</form>';
                return ret;
        };

        this.getOptions = function (question) {
                var retSel = '';
                var retAr = new Array();
                var options = question['options'];
                questions_hash[question['id']] = question;
                if (question['ftype'] == 3) {
                        retAr.push('<input class="gyp_input_answer" type="text" size="4" name="answer-' + question['id'] + '" />');
                } else {
                        if (question['ftype'] == 4) {
                                retSel += '<select class="gyp_select_answer" name="answer-' + question['id'] + '"><option value="">Choose one:</option>';
                        }
                        for (var i=0; i<options.length; i++) {
                                if (typeof options[i] == 'undefined') continue;
                                if (question['ftype'] == 4) {
                                        retSel += '<option class="gyp_input_answer" value="' + options[i][0] + '">' + options[i][1] + '</option>';
                                } else if (question['ftype'] == 1) {
                                        retAr.push('<input class="gyp_input_answer" type="radio" name="answer-' + question['id'] + '" value="' +  options[i][0] + '" /><span class="gyp_span_answer">' + options[i][1] + '</span>');
                                } else if (question['ftype'] == 2) {
                                        retAr.push('<input class="gyp_input_answer" type="checkbox" name="answer-' + question['id'] + '" value="' +  options[i][0] + '" /><span class="gyp_span_answer">' + options[i][1] + '</span>');
				} else if (question['ftype'] == 5) {
                                        retAr.push('<input class="gyp_input_answer" type="button" onclick="javascript: return voteSubmit(this, ' + options[i][0] + ')" name="answer-' + question['id'] + '" value="' +  options[i][1] + '" />');
                                } else {
                                }
                        }
                        if (question['ftype'] == 4) {
                                retSel += '</select>';
                        }
                }
                if (retSel.length > 0) {
                        retAr.push(retSel);
                }
                return retAr;
        };


	this.showResultsTable = function() {
		var t = document.getElementById('resarea');
		var elem = document.getElementById('showresbtn');
		if (t != undefined && elem != undefined) {
			t.style.display = '';
			elem.style.display = 'none';
		}
		var p = document.getElementById('gyp_polltable');
		if (p != undefined) {
			p.style.display = 'none';
		}
		return false;
	}

        this.drawResultsTable = function(style) {
                var aid = 0;
                var poll_votes = {};
                var ret = "";
		ret += '<a href="" id="showresbtn" onclick="return objPoll.showResultsTable()">Show results table</a>';
                ret += '<table class="gyp_restable" id="resarea" style="display: none;' + style + '" width="100%">';
		if (questions != undefined && questions[0] != undefined) {
	                ret += '<tr><td colspan="3"><strong>Poll #' + questions[0]['poll_id'] + ' Results</strong></td></tr>';
		}
                var sum = 0;
for (var t=0; t<results.length; t++) {
        if (typeof results[t] == 'undefined') continue;
                sum = 0;
                ret += '<tr><td colspan="3"><span class="gyp_span_res_question">' + results[t]['question'] + '</span></td></tr>';
                var answers = results[t]['options'];
                for (var i = 0; i < answers.length; i++) {
                        if (typeof answers[i] == 'undefined') continue;
                        sum += answers[i][2];
                }
                if (pollAnswer > 0)
                        sum += 1;
                for (var i = 0; i < answers.length; i++) {
                        if (typeof answers[i] == 'undefined') continue;
                        poll_answer = answers[i][1];
                        aid = answers[i][0];
                        poll_votes[aid] = answers[i][2];
                        if (pollAnswer > 0 && pollAnswer == aid)
                                poll_votes[aid]++;
                        if (typeof poll_answer == 'string' && aid >= 0) {
                                if (poll_votes[aid] > 0 && sum > 0) {
                                        var percent = poll_votes[aid] * 100/sum;
                                        width = Math.round(percent);
                                } else {
                                        width = 0;
                                }
                                label = width + '%';
                                ret += '<tr>';
                                ret += '<td width="20%">' + label + '</td>';
                                ret += '<td><span class="gyp_span_res_answer">' + poll_answer + '</span></td>';
                                ret += '<td width="100" style="background-color: white; width: 100px"><img src="http://www.getyourpoll.com/gypoll/empty.gif" style="height: 5px; width: ' + width + 'px" alt="' + label + '"/>';
                                ret += '</tr>';
                        }
                }
}
                ret += '</table>';
                return ret;
        };

        this.process = function() {
                if (poll_width >= 0 && poll_height >= 0) {
                        ret = '';
                        if (can_vote) {
				if (questions.length > 0) {
	                                ret += this.drawPollTable(style);
				}
	                        document.getElementById('pollarea').innerHTML = ret;
                        } else {
				if (results.length > 0) {
                                	ret += this.drawResultsTable(style);
				}
	                        document.getElementById('mainarea').innerHTML = ret;
                        }

		}
        };

        this.prepareForm = function(doc) {
                var link_to_site = '<a href="http://www.getyourpoll.com/gypoll" class="gyp_footer_link">Create your own web poll</a>';
                if (poll_width >= 0 && poll_height >= 0) {
                        if (typeof poll_bgcolor == 'string') {
                                style += 'background-color: ' + poll_bgcolor + ';';
                        }
                        if (typeof poll_fgcolor == 'string') {
                                style += 'color: ' + poll_fgcolor + ';';
                        }
                        if (typeof poll_tbl_border == 'string') {
                                style += 'border: ' + poll_tbl_border + ';';
                        }
                        var ret = "";
                        ret += '<table style="' + style + '" ';
                        if (poll_width > 0) {
                                ret += 'width="' + poll_width + '"';
                        }
                        ret += '>\n';
                        ret += '<tr><td colspan="2"><span id="gyp_span_message"></span></td></tr>';
                        ret += '<tr ';
                        if (poll_height > 0) {
                                ret += 'height="' + poll_height + '"';
                        }
                        ret += '>\n';
                        ret += '<td valign="top" ><div id="mainarea">\n';
                        ret += ('</div><div id="pollarea"></div></td></tr></table>\n' + link_to_site);
                        if (document.getElementById('pollhere') == undefined || typeof document.getElementById('pollhere') == 'undefined') {
                                var div = document.createElement('div');
                                div.id = 'pollhere';
                                div.innerHTML = link_to_site;
                                document.body.appendChild(div);
                        }
                        document.getElementById("pollhere").innerHTML = ret;
                }
        };
        
        this.errorHandler = function (desc, page, line, chr) {
                if (desc.indexOf('Line number') >= 0) 
                        return true;

                var message = 'JavaScript error occurred!;;'
                +'Error description: \t'+desc
                +';;Page address:      \t'+page
                +';;Line number:       \t'+line+' at ' + chr;
                // Let's put it inline, to avoid problems
//alert(message);
		return true;
                var url = "http://http://www.getyourpoll.com/gypoll/feedback.js?description=" + message;
//alert(url);
                if (document.getElementById('debug') != undefined) {
                        document.getElementById('debug').value = url;
                }

                var _span = document.createElement("span");
                var span = document.body.appendChild(_span);
                span.style.display = 'none';
                span.innerHTML = 'poll.openfun.org<s'+'cript></' + 'script>';
                        var s = span.getElementsByTagName("script")[0];
                        if (s.setAttribute) {
                                s.setAttribute('src', url); 
                                s.setAttribute('id', 'jsspan'); 
                                s.setAttribute('language', "JavaScript"); 
                        } else {
                                s.src = url;
                                s.id = 'jsspan';
                                s.language = "JavaScript";
                        }

                return true;

        };
};
var doc = document;
var objPoll = new Poll();
	if (typeof postload == 'function') {
		postload.call();
	};

//window.onerror = objPoll.errorHandler;
window.onload = function() {
        if (typeof poll_width == 'undefined') {
                poll_width = 0;
        }
        if (typeof poll_height == 'undefined') {
                poll_height = 0;
        }
	if (typeof noload == 'undefined') {
	        objPoll.prepareForm(doc);
	        objPoll.loadQuestions();
	};
}

function formSubmit(form) {
        return objPoll.formSubmit(form);
}

function voteSubmit(elem, option) {
//	alert(objPoll);
}