<div id="add_poll_form">
	<h2>{$lang.poll.create_poll}</h2>
	<!--add poll form-->
	<form name="add_poll_form" id="add_poll_form_form" method="post" action="{$site_root}/{$seo.poll}?sel=save_poll&par={$par}">
		<input type="hidden" name="page" value="{$page}">
		<input type="hidden" name="par" value="{$par}">
		<input type="hidden" name="poll_id" id="poll_id" value="0">
		<div id="add_new_poll_div" style="display:none;">&nbsp;&nbsp;<input type="button" value="{$lang.poll.add_new_poll}" onclick="resetAddForm();"></div>
		<p>
			{$lang.poll.status}:<br />
			<select style="margin: 5px 0; width: 80px;" name="status" id="status">
				<option value="1">{$lang.poll.status_vals.1}</option>
				<option value="0">{$lang.poll.status_vals.0}</option>
			</select>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		</p>
		<p>
			{$lang.poll.expiration}:<br />
			<input type="text" name="expiration" id="expiration" size="3" style="width:80px; margin: 5px 0;"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            <label style="vertical-align: text-top;" for="never">{$lang.poll.never_exp}</label><input style="margin-left: 10px;" id="never" type="checkbox" name="never_expire" value="1" checked="checked" onclick="initExpiration($(this).attr('checked'));"/>
		</p>
		<p>	
			<label for="comments">{$lang.poll.allow_comments}</label><input style="margin-left: 10px;" id="comments" type="checkbox" name="allow_comments" value="1" checked="checked">
		</p>
		<div id="answers" style="margin-top: 10px;">
			<div id="question">
				<div style="width: 100%;">{$lang.poll.question}:<br /></div>
				<div style="margin: 5px 0;">
                    <input type="text" onkeyup="BadWords('question_1');" id="question_1" name="question" style="width:363px; "/>
				    <a style="vertical-align: bottom;" href="#" onclick="addAnswer(); return false;">{$lang.poll.add_answer}</a>
                </div>
                <div id="bad_div_question_1" class="bad_div_left"></div>
			</div>
			<p>
				{$lang.poll.category}:<br />
				<select style=" margin: 5px 0;" name="category_id" id="category_id">
					{foreach from=$all_categories item=item}
					<option value="{$item.category_id}" {if $curr_category.category_id==$item.category_id}selected="selected"{/if}>{$item.name}</option>
					{/foreach}
				</select>
			</p>
			<div>
				<div>{$lang.poll.show_groups}:<br /></div>
			    <div style="margin-top: 5px; display: table; width: 100%;">
                    <dl class="float_left" style="width: 150px;">
    				{foreach name=group from=$groups item=item}
    					<dd><input type="checkbox" name="group_ids[]" id="group_ids_{$item.group_id}" value="{$item.group_id}" checked="checked">&nbsp;
    					{$item.name}
    					</dd>
    					{if $smarty.foreach.group.iteration is div by 2}
            			</dl>
            			<dl class="float_left" style="width: 150px;">
            			{/if}
            			{/foreach}
            		</dl>
                </div>
			</div>
		</div>
		<p>
			<input class="float_left" id="save_button" type="button" value="{$lang.button.add}" onclick="addPoll_save();" style="margin: 10px 0;"/>
		</p>
	</form>
	<!--/add poll form-->
</div>
<div style="display: none;">
	<div id="answer_source">
		<div class="tr_answer" >
			<div style="width: 100%;">{$lang.poll.answer}<span style=" margin: 5px 0;" class="answer_counter"></span>:<br /></div>
			<div style="margin: 5px 0;">
                <input type="text" name="answer[]" id="answer_%i%" onkeyup="BadWords('answer_%i%');" style="width:290px;">
    			#<input type="text" name="color[]" class="colorpick" style="width:60px;">&nbsp;<a style="vertical-align: bottom;" href="#" onclick="removeAnswer($(this)); return false;">{$lang.poll.crop_answer}</a>
            </div>
            <div id="bad_div_answer_%i%" class="bad_div_left"></div>
		</div>
	</div>
</div>
<script type="text/javascript">


	page = '{$page}';
	category_id = '{$curr_category.category_id}'
	

	min_answers = 2;

	resetAddForm();

	{if $poll_info_json}
	poll_info = getJQData('{$poll_info_json}');
	setEditFormData(poll_info);
	{/if}

	{literal}
	function resetAddForm(){
		$("#add_poll_form #add_new_poll_div").hide();
		$("#add_poll_form input[name=poll_id]").val('0');
		$("#add_poll_form select[name=status]").val('1');
		$("#add_poll_form input[name=expiration]").val('');
		$("#add_poll_form input[name=never_expire]").attr('checked','checked');
		initExpiration();
		$("#add_poll_form input[name=allow_comments]").attr('checked','checked');
		$("#add_poll_form input[name=question]").val('');
		$("#add_poll_form .tr_answer").remove();
		initAnswers();
		$("#add_poll_form select[name=category_id]").val(category_id);
		$('input[name="group_ids[]"]:checked').each(function(){
			$(this).attr("checked",'checked');
		});
		$("#add_poll_form #save_button").val('{/literal}{$lang.button.add}{literal}');
	}

	function initExpiration(){
		checked_never = $("input[name=never_expire]").attr('checked');
		if (checked_never){
			$("input[name=expiration]").val('');
			$("input[name=expiration]").attr('disabled','disabled');
		}else{
			$("input[name=expiration]").removeAttr('disabled');
		}
	}

	function initAnswers(){
		for(i=1;i<=min_answers;i++){
			addAnswer();
		}
		return;
	}

	function addAnswer(text,color){
		count = $("#answers .tr_answer").length; 
		source = $("#answer_source").html().replace(/%i%/g,count);
		if (count == 0){
			$("#question").after(source);
		}else{
			$("#answers .tr_answer:last").after(source);
		}

		$("#answers .answer_counter").each(function(i){
			$(this).html(i+1);
		});
		initColorPickers();
		$("#answers input[name='answer[]']:last").focus().val(text);
		$("#answers input[name='color[]']:last").val(color);
	}

	function initColorPickers(){
		setColors();
		inpt=[];
		$('.colorpick').each(function(i){
			inpt[i] = $(this);
			inpt[i].ColorPicker({
				color: '#'+(inpt[i].val()?inpt[i].val():getRandColor()),
				onShow: function (colpkr) {
					$(colpkr).fadeIn(500);
					return false;
				},
				onHide: function (colpkr) {
					$(colpkr).fadeOut(500);
					return false;
				},
				onChange: function (hsb, hex, rgb) {
					inpt[i].val(hex);
				},
				onSubmit: function(hsb, hex, rgb) {
					inpt[i].val(hex);
					inpt[i].ColorPickerHide();
				}
			});
		});
		$('.colorpicker').css('z-index','1000000');
	}

	function setColors(){
		$("#answers .colorpick").each(function(){
			if (!$(this).val())
				$(this).val(getRandColor());
		});
	}

	function removeAnswer(link_remove){
		if ($("#answers .tr_answer").length <= min_answers){
			//$("#answers input[name=answer[]]:last").focus();
			$('#answers input[name="answer[]"]:last').each(function(){
				$(this).focus();
			});
			return false;
		}
		link_remove.parent().parent().remove();
		$("#answers .tr_answer").length = $("#answers .tr_answer").length-1;
		$("#answers .answer_counter").each(function(i){
			$(this).html(i+1);
		});
		//$("#answers input[name=answer[]]:last").focus();
		$("#answers input[name='answer[]']:last").each(function(){
			$(this).focus();
		});
	}

	function addPoll_save(){
		question_val = $("input[name=question]").val();
		count_with_vals=0;
		
		$("#answers input[name='answer[]']").each(function(i){
			$(this).val() ? count_with_vals++ : '';
		});
		
		if (question_val==''){
			alert("{/literal}{$lang.poll_errors.empty_question|escape:javascript}{literal}");
			return false;
		}
		
		if (count_with_vals < min_answers){
			alert("{/literal}{$lang.poll_errors.min_answers|escape:javascript}{literal}"+min_answers);
			return false;
		}
		
		if (!$("input[name='group_ids[]']:checked").val()){
			alert("{/literal}{$lang.poll_errors.addPoll_empty_groups|escape:javascript}{literal}");
			return false;
		}
		
		param = $('#add_poll_form_form').serialize();
		$.ajax({
			type: 'POST',
			url: 'poll.php',
			data: 'sel=save_poll&' + param,
			success: function(msg){
				if(msg == "ok"){
					location.href='{/literal}{$site_root}/{$seo.poll}{literal}';
				} else {
					ShowAjaxError('', msg);
				}
			}
		});
	}

	function setEditFormData(poll_info){
		$("#header_form").html('{/literal}{$lang.poll.edit_poll}{literal}');
		$("#add_poll_form input[name=poll_id]").val(poll_info.poll_id);
		$("#add_poll_form select[name=status]").val(poll_info.status);
		if (poll_info.expire_days){
			$("#add_poll_form input[name=expiration]").val(poll_info.expire_days);
			$("#add_poll_form input[name=never_expire]").removeAttr('checked');
		}else{
			$("#add_poll_form input[name=expiration]").val('');
			$("#add_poll_form input[name=never_expire]").attr('checked','checked');
		}
		initExpiration();
		if(poll_info.allow_comments=='1'){
			$("#add_poll_form input[name=allow_comments]").attr('checked','checked');
		}else{
			$("#add_poll_form input[name=allow_comments]").removeAttr('checked');
		}
		$("#add_poll_form input[name=question]").val(poll_info.question);
		$("#add_poll_form .tr_answer").remove();
		for(i=0;i<poll_info["answers"].length;i++){
			addAnswer(poll_info["answers"][i]["text"],poll_info["answers"][i]["color"]);
		}
		$("#add_poll_form select[name=category_id]").val(poll_info.category_id);

		$('input[name="group_ids[]"]').removeAttr('checked');
		for(var i in poll_info.groups){
			$('#group_ids_'+poll_info.groups[i]).attr('checked', 'checked');
		}

		$('#add_button').hide();$('#add_poll_form').show();
		$("#add_poll_form #save_button").val('{/literal}{$lang.button.save}{literal}');
		return;
	}

	function deletePoll(poll_id){
		ajaxLoadingImage(1, false);
		str = 'poll_id='+poll_id;

		$.post('./admin_poll.php?sel=delete_poll',str,function(data){
			data = getJQData(data);
			if (data['success']=='1'){
				showNoticeOnEl(data['msg'],$("#delete_link"+poll_id));
				$("#tr"+poll_id).remove();
				if ($("tr[param=poll_tr]").length==0){
					location.href="./admin_poll.php?sel=view_polls&category_id="+category_id+"&filter="+filter+"&username="+username+"&page="+(page-1);
				}
			}else{
				showNoticeOnEl(data['msg'],$("#delete_link"+poll_id));
			}
			ajaxLoadingImage(0, false);
		});
	}
{/literal}
</script>
