$(document).ready(function() {
	$("<script>").attr("type","text/javascript").attr("src","/adm/js/lycos/3.0/modules/poll/vkChart.js").appendTo("head");
});


var poll = $.inherit( Module, {
	__constructor: function( moduleDiv ) {
		this.__base( moduleDiv );
		this.type="poll";
		this.isResizing=true;
		this.keepAspectRatio=false;
	},

	initialize: function(){
		this.getPollData( createRef( this, this.loadContent ) );
	},

	getOptionsFromDb: function( callbackFunc ) {
		var _this=this;
		this.ajaxPost('getOptions', {}, function(data,textSuccess) {
			(callbackFunc||$.noop)(data);
		});
	},

	setOptionsDb: function( opts, callbackFunc ) {
		this.ajaxPost('setOptions', opts, function(data,textSuccess){
			(callbackFunc||$.noop)(data);
		});
	},

	getPollData:function( callbackFunc ){
		this.ajaxPost('getPollData', {}, function(data,textSuccess){
			(callbackFunc||$.noop)(data);
		});
	},

	loadContent:function(data){
		var _this = this;
		opts = eval( "(" + data.response + ")" );
		$("#poll_content",this.container).empty();
		$("<div>").attr("id","poll_result").attr("style","display:none;width:500px;height:350px;margin:auto;").appendTo($("#poll_content",this.container));
		$("<img>").attr("src","/adm/images/poll_addon/close.png").attr("style","position:absolute; top:5px; right:5px; z-index:9999;")
			.click(function(){
				$("#poll_result",_this.container).slideUp();
				$("#graph",_this.container).empty();
			}).appendTo($("#poll_result",this.container)).wrap('<a href="#"></a>');

		$("<div>").attr("id","graph").attr("style","width:500px;height:350px;").appendTo($("#poll_result",this.container));
		$("<img>").attr("src","/adm/images/tab_loader.gif").attr("style","position:relative;top:40%;").appendTo($("#graph",this.container));

		switch(opts.options.status){
			case"EDIT":
				if(!(_this.isPublished)){
					$("<div>").attr("id","poll_status_message").attr("class","poll_status_message_rd").html("POLL IS NOT READY FOR PUBLISHING").appendTo($("#poll_content",this.container));
					$("<fieldset>").attr("id","edit_poll").attr("class","poll_fieldset").appendTo($("#poll_content",this.container));
					$("<legend>").attr("align","center").html("Enter poll data").appendTo($("#edit_poll",this.container));
					$("<div>").attr("id","title_settings_div").attr("class","title_settings_div").appendTo($("#edit_poll",this.container));
					$("<label>").attr("for","poll_title").html("Poll Title:").attr("style","margin:2px 5px 2px 0;").appendTo($("#title_settings_div",this.container));
					$("<input>").attr("id","poll_title").val(opts.options.title).attr("name","title").attr("type","text").attr("style","margin:2px 20px 2px 0;").appendTo($("#title_settings_div",this.container));
					$("<label>").attr("for","display_title").html("Display Title:").attr("style","margin:2px 5px 2px 0;").appendTo($("#title_settings_div",this.container));
					$("<input>").attr("type","checkbox").attr("id","display_title").attr("value","Y").attr("name","display_title").attr("style","margin:2px 20px 2px 0;").appendTo($("#title_settings_div",this.container));
					if(opts.options.display_title=="Y"){
						$("#display_title",this.container).attr("checked","checked");
					}
					else{
						$("#display_title",this.container).attr("checked","");
					}
					$("<div>").html("Enter poll question:").appendTo($("#edit_poll",this.container));
					$("<textarea>").attr("id","poll_question").attr("rows","2").attr("style","margin-top:5px; width:inherit;").val(opts.options.subject).appendTo($("#edit_poll",this.container));
					$("<div>").attr("id","poll_answers").attr("style","padding:30px 0 0 0;").html("Enter poll answers:").appendTo($("#edit_poll",this.container));
					if(opts.answers){
						$.each(opts.answers,function(i,answer){
							$("<br>").appendTo($("#poll_answers",this.container));
							$("<span>").html(answer.number+".").attr("style","margin-right:5px;").appendTo($("#poll_answers",this.container));
							$("<input>").attr("id","q_"+answer.number).val(answer.answer).attr("name","q").attr("type","text").attr("style","margin:2px 0 2px 0;").appendTo($("#poll_answers",this.container));
							answerCount=i+2;
						});
					}
					else{
						for(i=1;i<4;i++){
							if(i>0){
								$("<br>").appendTo($("#poll_answers",this.container));
							}
							$("<span>").html(i+".").attr("style","margin-right:5px;").appendTo($("#poll_answers",this.container));
							$("<input>").attr("id","q_"+i).attr("name","q").attr("type","text").attr("style","margin:2px 0 2px 0; width:inherit;").appendTo($("#poll_answers",this.container));
						}
						answerCount=i;
					}
					$("<input>").attr("type","button").attr("value","Add answer").attr("id","add_answer_btn").attr("style","position:relative; float:left; margin-top:15px;").appendTo($("#edit_poll",this.container))
						.click(function(){
							$("<span>").html("<br>"+answerCount+".").attr("style","margin-right:10px;").appendTo($("#poll_answers",this.container));
							$("<input>").attr("id","q_"+answerCount).attr("name","q").attr("type","text").attr("style","margin:2px 0 2px 0; width:inherit;").appendTo($("#poll_answers",this.container));
							answerCount++;
						});
					$("<fieldset>").attr("id","poll_colors").attr("class","poll_fieldset").appendTo($("#poll_content",this.container));
					$("<legend>").attr("align","center").html("Select poll color theme").appendTo($("#poll_colors",this.container));
					var pollThemes=["dark","light"];
					for(i=0;i<pollThemes.length;i++){
						$("<div>").attr("id","theme_example_"+pollThemes[i]).attr("class","theme_example float_left").appendTo($("#poll_colors",this.container));
						$("<div>").attr("class","theme_header_"+pollThemes[i]).html("Question").appendTo($("#theme_example_"+pollThemes[i],this.container));
						$("<div>").attr("class","theme_"+pollThemes[i]).html("Answer").appendTo($("#theme_example_"+pollThemes[i],this.container));
						$("<div>").attr("class","theme_header_"+pollThemes[i]).html("Footer").appendTo($("#theme_example_"+pollThemes[i],this.container));
						$("<input>").attr("id","radio_color_"+pollThemes[i]).attr("type","radio").attr("name","poll_colors").attr("value",pollThemes[i]).attr("style","padding:10px !important;").appendTo($("#theme_example_"+pollThemes[i],this.container));
					}
					$("#radio_color_"+opts.options.theme).attr("checked","true");$("<fieldset>").attr("id","poll_apperance").attr("class","poll_fieldset").appendTo($("#poll_content",this.container));
					$("<legend>").attr("align","center").html("Select result graph style").appendTo($("#poll_apperance",this.container));
					var graphImages=["bar","sidebar","stackedbar"];
					for(i=0;i<graphImages.length;i++){
						$("<div>").attr("id","div_a"+i).attr("class","poll_imgDiv float_left").appendTo($("#poll_apperance",this.container));
						$("<img>").attr("style","margin:2px;").attr("src","/adm/images/poll_addon/"+graphImages[i]+".png").appendTo($("#div_a"+i,this.container));
						$("<input>").attr("id","radio_"+graphImages[i]).attr("type","radio").attr("name","poll_type").attr("value",graphImages[i]).attr("class","poll_radio").appendTo($("#div_a"+i,this.container));
					}
					$("#radio_"+opts.options.poll_type).attr("checked","true");$("<div>").attr("id","button_div").appendTo($("#poll_content",this.container));
					$("<input>").attr("type","button").attr("id","save_poll_btn").attr("value","Save poll data").appendTo($("#button_div",this.container))
						.click(function(){
							_this.savePollData(createRef(_this,_this.loadModule));
						});
				}
				break;
			case"PREVIEW":
				if(!(_this.isPublished)){
					$("<div>").attr("id","poll_status_message").attr("class","poll_status_message_rd").html("POLL IS NOT READY FOR PUBLISHING").appendTo($("#poll_content",this.container));
					$("<fieldset>").attr("id","running_poll").attr("class","poll_fieldset").appendTo($("#poll_content",this.container));$("<legend>").attr("align","right").html("Running poll").appendTo($("#running_poll",this.container));
					if(opts.options.display_title=="Y"){
						$("<div>").attr("id","div_title").attr("class","poll theme_title_"+opts.options.theme).html(opts.options.title).appendTo($("#running_poll",this.container));
					}
					$("<div>").attr("id","div_subject").attr("class","poll theme_header_"+opts.options.theme).appendTo($("#running_poll",this.container));
					$("<span>").attr("class","div_subject_text").html(opts.options.subject).appendTo($("#div_subject",this.container));
					var b=this.container;
					$.each(opts.answers,function(i,answer){
						$("<div>").attr("id","answer_"+i).attr("class","poll theme_"+opts.options.theme).appendTo($("#running_poll",this.container));
						if(i>0){
							$("<br>").appendTo($("#poll_answers",b));
						}
						$("<input>").attr("type","radio").attr("name","answer").attr("value",answer.number).appendTo($("#answer_"+i,b));$("<span>").html(answer.answer).attr("style","margin-left:10px;").appendTo($("#answer_"+i,b));
					});
					$("<div>").attr("id","div_footer").attr("class","poll theme_header_"+opts.options.theme).html("&nbsp;").appendTo($("#running_poll",this.container));
					$("<fieldset>").attr("id","poll_results").attr("class","poll_fieldset").appendTo($("#poll_content",this.container));
					$("<legend>").attr("align","right").html("Poll results").appendTo($("#poll_results",this.container));
					$("<img>").attr("src","/adm/images/poll_addon/"+opts.options.poll_type+".png").attr("style","border-width:2px;border-color:gray;border-style:solid;").appendTo($("#poll_results",this.container));
					$("<div>").attr("id","poll_btns").attr("style","margin:15px 0 10px 0;").appendTo($("#poll_content",this.container));
					$("<div>").attr("id","buttons_div").attr("style","display:block;").html("&nbsp;").appendTo($("#poll_btns",this.container));
					$("<input>").attr("type","button").attr("value","Finish").attr("style","margin-left:10px; float:right;")
						.click(function(){
							_this.pollReady(createRef(_this,_this.loadModule));
						})
						.appendTo($("#buttons_div",this.container));
					$("<input>").attr("type","button").attr("value","Edit poll").attr("style","margin-left:10px; float:right;")
						.click(function(){
							_this.editPoll(createRef(_this,_this.loadModule));
						})
						.appendTo($("#buttons_div",this.container));
						$("<div>").html("NOTE: You will not be able to change any poll data after you click \"finish\" button!").appendTo($("#poll_btns",this.container));
				}
				break;
			case"RUN":
				if(!(_this.isPublished)){
					$("<div>").attr("id","poll_status_message").attr("class","poll_status_message_gr").html("POLL IS READY FOR PUBLISHING").appendTo($("#poll_content",this.container));
				}
				if(opts.options.display_title=="Y"){
					$("<div>").attr("id","div_title").attr("class","poll theme_title_"+opts.options.theme).html(opts.options.title).appendTo($("#poll_content",this.container));
				}
				$("<div>").attr("id","div_subject").attr("class","poll theme_header_"+opts.options.theme).appendTo($("#poll_content",this.container));
				$("<span>").attr("class","subject_text").html(opts.options.subject).appendTo($("#div_subject",this.container));
				var b=this.container;
				$.each(opts.answers,function(i,answer){
					$("<div>").attr("id","answer_"+i).attr("class","poll theme_"+opts.options.theme).appendTo($("#poll_content",b));
					$("<input>").attr("type","radio").attr("name","answer").attr("value",answer.number).appendTo($("#answer_"+i,b));
					$("<span>").attr("style","margin-left:10px;").html(answer.answer).appendTo($("#answer_"+i,b));
				});
				$("<div>").attr("id","btns").attr("class","poll theme_header_"+opts.options.theme).appendTo($("#poll_content",this.container));
				$("<span>").attr("class","p_btn").html("View results")
					.click(function(){
						$('#poll_result',_this.container).slideDown();
						_this.getPollData(createRef(_this,_this.viewPollResults));
					})
					.appendTo($("#btns",this.container));
				$("<span>").attr("class","p_btn").html("Vote")
					.click(function(){
						_this.pollVote();
					})
					.appendTo($("#btns",this.container));
				if(!(_this.isPublished)){
					$("<div>").attr("id","poll_btns").attr("style","float:right; margin:15px 0 10px 0;").appendTo($("#poll_content",this.container));
					$("<input>").attr("type","button").attr("value","End poll")
						.click(function(){
							_this.endPoll(createRef(_this,_this.loadModule));
						})
						.appendTo($("#poll_btns",this.container));
				}
				break;
			case"END":
				$("<div>").attr("id","div_subject").attr("class","theme_header_"+opts.options.theme).appendTo($("#poll_content",this.container));
				$("<span>").attr("class","subject_text").html(opts.options.subject).appendTo($("#div_subject",this.container));
				$("<span>").attr("class","p_btn").html("view results")
					.click(function(){
						$('#poll_result',_this.container).slideDown();
						_this.getPollData(createRef(_this,_this.viewPollResults));
					})
					.appendTo($("#div_subject",this.container));
				break;
			default:
				$("#poll_content",this.container).html("<p>UNKNOWN POLL STATUS</p>");
		}},

		viewPollResults: function(data){
			$("#graph",this.container).empty();
			var _this=this;data=eval("("+data.response+")");
			var chartData=new Array();
			var chartLabels=new Array();
			$.each(data.answers,function(i,answer){
				chartData[i]=answer.vote_count;
				chartLabels[i]=answer.answer;
			});
			var myChart=new vkChart($("#graph",this.container));
			myChart.title=data.options.title;
			myChart.type=data.options.poll_type;
			myChart.data=chartData;
			myChart.labels=chartLabels;
			myChart.init();
		},

		randomString: function(){
			var chars="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
			var string_length=64;
			var randomstring='';
			for(var i=0;i<string_length;i++){
				var rnum=Math.floor(Math.random()*chars.length);
				randomstring+=chars.substring(rnum,rnum+1);
			}
			return randomstring;
		},

		getCookie: function(c_name){
			var i, x, y, ARRcookies = document.cookie.split(";");
			for(i=0;i<ARRcookies.length;i++){
				x = ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
				y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
				x = x.replace(/^\s+|\s+$/g,"");
				if(x==c_name){
					return unescape(y);
				}
			}
			return false;
		},

		setCookie: function(c_name,value,exdays){
			var exdate=new Date();
			exdate.setDate(exdate.getDate()+exdays);
			var c_value=escape(value)+((exdays==null)?"":"; expires="+exdate.toUTCString());
			document.cookie=c_name+"="+c_value;
		},

		pollVote: function(callbackFunc){
			var _this = this;
			var client_ip = null;
			var cc = this.getCookie( "poll"+this.id );
			if( !cc ) {
				this.setCookie( "poll"+this.id, this.randomString(), 100 );
				cc = this.getCookie("poll"+this.id);
			}

			var p_vote_array=$('input[name="answer"]',this.container);
			var p_vote_number = false;
			$.each(p_vote_array,function(i,radio){
				if(radio.checked)
					p_vote_number=radio.value;
			});
			if(p_vote_number!=false)
			{
				_this.ajaxPost('pollVote',{"vote_num":p_vote_number,"cookie":cc,"client_ip":cc},function(data,textSuccess){
					$("<div>").attr("id","notification").html("Your vote was recorded").insertBefore("#body").fadeIn("slow","linear").delay(5000).fadeOut("slow","linear");
					(callbackFunc||$.noop)(data);
				});
			}
			else
			{
				$.fn.colorbox({width:"380px",height:"200px",html:"<div class='poll_popup' style='color:#000'>Please select one of the options.</div>"});
			}
/*
			$.getJSON("http://tri-webon1.bo3.lycos.com/adm/getip.php?callback=?", function(data) {
				client_ip = data.ip;
				var p_vote_array=$('input[name="answer"]',this.container);
				var p_vote_number = false;
				$.each(p_vote_array,function(i,radio){
					if(radio.checked)
						p_vote_number=radio.value;
				});
				if(p_vote_number!=false)
				{
					_this.ajaxPost('pollVote',{"vote_num":p_vote_number,"cookie":cc,"client_ip":cc},function(data,textSuccess){
						$("<div>").attr("id","notification").html("Your vote was recorded").insertBefore("#body").fadeIn("slow","linear").delay(5000).fadeOut("slow","linear");
						(callbackFunc||$.noop)(data);
					});
				}
				else
				{
					$.fn.colorbox({width:"380px",height:"200px",html:"<div class='poll_popup' style='color:#000'>Please select one of the options.</div>"});
				}
			});
*/
		},

		endPoll: function(callbackFunc){
			this.ajaxPost('endPoll', {}, function(data,textSuccess){
				(callbackFunc||$.noop)(data);
			});
		},

		pollReady:function(callbackFunc){
			this.ajaxPost('pollReady',{},function(data,textSuccess){
				(callbackFunc||$.noop)(data);
			});
		},

		savePollData:function(callbackFunc){
			var p_title=$("#poll_title").val();
			var p_display_title=$("#display_title");
			if(p_display_title[0].checked){
				display_title=p_display_title[0].value;
			}
			else{
				display_title="N";
			}
			var p_theme=$('input[name="poll_colors"]');

			$.each(p_theme,function(i,radio){
				if(radio.checked)
					p_theme=radio.value;
			});
			var p_type_array=$('input[name="poll_type"]');

			$.each(p_type_array,function(i,radio){
				if(radio.checked)
					p_type=radio.value;
			});
			var p_question=$("#poll_question").val();
			var p_answersArray=$('input[name="q"]');
			var pa=Array();
			$.each(p_answersArray,function(i,answer){
				pa[i]=answer.value;
			});

			opts={"pq":p_question,"pt":p_type,"pa":pa,"ptheme":p_theme,"p_title":p_title,"p_display_title":display_title};
			this.ajaxPost('savePollData',opts,function(data,textSuccess){
				(callbackFunc||$.noop)(data);
			});
		},

		editPoll:function(callbackFunc){
			this.ajaxPost('editPoll',opts,function(data,textSuccess){
				(callbackFunc||$.noop)(data);
			});
		},

		loadModuleCallback:function(data,textStatus){
			this.moduleData=data;
			this.$poll_content=this.container.find("#poll_content");
			this.container[0].innerHTML=data.html;
			if(this.postSaveData){
				this.handleModuleSaveResult(this.postSaveData);
				this.setOptionsDb(this.postSaveData.options);
				this.postSaveData='';
			}
			this.getPollData(createRef(this,this.loadContent));
			this.addDragHandle(data);

			if(this.isResizing){
				this.addResizing();
			}
		},

		appropriatelySizeModule:function(floatValue){
			var moduleContainerDiv=$('.module-container',this.element);
			var adjustedModuleWidth=null;
			var adjustedModuleHeight=null;
			if((this.element.parent().attr('id')=='header') || (this.element.parent().attr('id')=='footer')){
				adjustedModuleHeight='100px';
			}
			else if(this.element.parent().attr('id')=='content') {
				if(floatValue=='none'){
					adjustedModuleWidth=this.element.parent().width()+'px';
				}
				else{
					adjustedModuleWidth=(this.element.parent().width()*.5)+'px';
				}
			}
			else if(this.element.parent().attr('id')=='sidebar') {
				if(floatValue=='none'){
					adjustedModuleWidth=this.element.parent().width()+'px';
				}
				else{
					adjustedModuleWidth=(this.element.parent().width()*.5)+'px';
				}
			}
			if(adjustedModuleWidth){
				this.element.css({'width':adjustedModuleWidth});
			}
			if(adjustedModuleHeight){
				this.element.css({'height':adjustedModuleHeight});
			}
			if( adjustedModuleWidth || adjustedModuleHeight ) {
				moduleContainerDiv.css({'width':'100%','height':'100%'});
			}
		}
});
