$(function() {
	var path=''; /*  the complete path from the root to the smooth_poll  */
    $('.pollWrapper').each(function(){
    var ref = $(this).attr('id');
    var loader = $('#l-'+ref);
    var pollcontainer = $('#d-'+ref);
    
    	loader.fadeIn();
	    $.post(path+'poll.php',{auth:'y',r:ref},function(d) 
	    {
	        pollcontainer.each(function()
	        {
	        	$(this).html(d)
	        	animateResults(ref);
	    	});
		        submitForm(ref); 
	         
		    $('#viewresult-'+ref).live('click', function() 
		    {
		        viewResult(ref);
		        return false;
	   		 });
	   		 
	    	$('#vote-'+ref).live('click',function() {
	            vote(ref);
	            return false;
	        });
	        styleIt(ref);
	        $('#'+ref).live('mouseout',function(){$('#thxMsg-'+ref).hide(800);});
	        loader.fadeOut();
	    });
		
	    $('#nimda-'+ref).live('click',function() 
		{
	        return false;
	    });
	    
		$('#nimda-'+ref).live('dblclick',function() 
		{
	        loader.fadeIn();
	        $.post(path+'poll.php', { cmd: 'letMeIn',auth: 'y',r:ref},function(d) {
	            pollcontainer.fadeOut(1000,function() 
	            {
	                $(this).html(d).fadeIn();
	                loader.fadeOut();
	            });
	        });
	        return false;
	    });
	    
	     $('#go-'+ref).live('click',
	    function() {
	        loader.fadeIn();
	        var resu = $('#resu-'+ref).val();
	        var ssap = $('#ssap-'+ref).val();
	        $.post(path+'poll.php', { auth: 'y',u: resu, p: ssap,r:ref },function(d) {
	            pollcontainer.fadeOut(1000,function() {
	                $(this).html(d).fadeIn();
	                styleIt(ref);
	                loader.fadeOut();
	            });
	        })
	    });
	    
	    $('#logout-'+ref).live('click',function() {
	        loader.fadeIn();
	        $.post(path+'poll.php', {cmd: 'getMeOut', auth: 'y',r:ref},function(d) {
	            pollcontainer.fadeOut(1000,function() 
	            {
	                $(this).html(d).fadeIn();
	                styleIt(ref);
	                 loader.fadeOut();
	            });
	        });
	    });
	    
		$('#lang-'+ref).live('click',function(){
			var elem=$(this).offset();
			$(this).next().css({'top':elem.top+22,'left':elem.left});
			$(this).next().toggle(200);
			return false;
		});
		
		$('#dd-'+ref+' .langz').live('click',function()
		{	
			var language=$(this).text();
			if(!confirm('You are going to change the poll language to'+language+', Are you sure ?'))
			{$('#dd-'+ref).toggle(400);return false;}
			pollcontainer.fadeOut(500);
			loader.fadeIn();
			$.post(path+'poll.php',{cmd:'changeLang',r:ref,l:language,auth:'y'},function(d)
			{
				pollcontainer.html(d).fadeIn(function() 
		            {
		                 loader.fadeOut();
		            }
            	);
			})
			return false;
		})
		
	     $('#menu-'+ref).live('click',function() {
	        $('#'+ref+' .adBtn').show(500);
	        $('#'+ref+' .open').each(function() {
	            $(this).toggle(500);
	            $(this).toggleClass('open');
	        })
	        return false;
	    });
	    
	    
	    $('#newPoll-'+ref).live('click',
	    function() {
	        $('#np-'+ref).toggle(500);
	        $('#np-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
	    
	    
	 	$('#addPollOpt-'+ref).live('click',function() {
	        var optNum = ($('#'+ref+' .newPoll').find('input[type=text]:not(input[name=pollQues])').length) + 1;
	        var newOpt = $('<tr><td></td><td><input type="text" class="txtInp" name="pollOpt[]" /> ' + optNum + '</td></tr>');
	        var addOpt = $('#addPollOpt-'+ref);
	        newOpt.insertBefore(addOpt.parent().parent());
	        return false;
	    });
	    
	    
	     $('#rmvPollOpt-'+ref).live('click',
	    function() {
	        var index = $('#'+ref+' .newPoll').find('input[type=text]:not(input[name=pollQues])').length;
	        if (index > 2) {
	            $(this).parent().parent().prev().prev().remove();
	        } else {
	            alert('At least two options');
	        };
	        return false;
	    });
	    
	    
	    
	    $('#publish-'+ref).live('click',function() 
	     {
	        var empty = 0;
	        $('#'+ref+' #pollTable input').each(function() {
	            if ($(this).val() == '') {
	                empty = 1;
	            };
	        });
	        
	        if (empty) {
	            alert('Empty field(s) have been detected please fill them in , and try again !');
	            return false;
	        }
	        
	        var activate = $('#defShow-'+ref).attr('checked');
	        var show='n';
	        if(activate)
	        {
	        	show='y';
	        }else{show='n';}
	        var save = $(this).attr('name');
	        var qId = '';
	        if (save == 'save') {
	            qId = $(this).attr('class');
	        }
	        var opts = Array();
	        var question = $('#'+ref+' .newPoll').find('input[name=pollQues]').val();
	        if (!save) {
	            var tableData = $('#'+ref+' #pollTable').html();
	        }
	        $('#'+ref+' .newPoll').find('input[type=text]:not(input[name=pollQues])').each(function(i) {
	            opts[i] = $(this).val();
	        });
	         loader.fadeIn();
	        $.post(path+'poll.php', {cmd: 'publish', q: question, o: opts, s: save,quesId: qId,r:ref,a:show,auth:'y'},function(d) {
	            $('#'+ref+' #pollTable').fadeOut(500,function()
	            {
	                $('#'+ref+' #pollTable').html(d).fadeIn(500,function() {
	                    if (!save) {
	                        setTimeout(function() {$('#pollTable').html(tableData);},3000)
	                    };
	                    loader.fadeOut();
	                });
	            })
	        });
	        return false;
	    });
	    
	    $('#editPoll-'+ref).live('click',
	    function() {
	        $('#ep-'+ref).toggle(500);
	        $('#ep-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
	    
	    
	    
	    $('#'+ref+' .qList').live('click',
	    function() {
	        var id = $(this).attr('id');
	        if (id != null && id != undefined && id != '') {
	            var ques = $(this).text();
	            loader.fadeIn();
	            $.post(path+'poll.php', {cmd: 'editPoll',q: ques,qId: id, r:ref,auth: 'y'},function(d) {
	                $('#'+ref+' #d-'+ref).fadeOut(500,function() {
	                    $('#'+ref+' #d-'+ref).html(d).fadeIn(function() {
	                        $('#'+ref+' .newPoll').toggle(500);
	                        loader.fadeOut();
	                    });
	                })
	            });
	        }
	        return false;
	    });
	    
	    
	    $('#delPoll-'+ref).live('click',
	    function() {
	        $('#dp-'+ref).toggle(500);
	        $('#dp-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
	    
	    
	    $('#'+ref+' .delList').live('click',function() {
        if (!confirm('You are going to delete this poll,Are you sure ?')) {
            return false;
        }
        var id = $(this).attr('id');
        if (id != null && id != undefined && id != '') {
            var ques = $(this).text();
            loader.fadeIn();
            $.post(path+'poll.php', {cmd: 'delPoll',q: ques,qId: id,r:ref,auth: 'y'},function(d) {
                $('#'+ref+' #d-'+ref).fadeOut(500,function() {
                    $('#'+ref+' #d-'+ref).html(d).fadeIn(function() {
                        loader.fadeOut();
                    });
                })
            });
        }
        return false;
    });
	    
    
        $('#nimda_set-'+ref).live('click',
	    function() {
	        $('#as-'+ref).toggle(500);
	        $('#as-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
	    
	     $('#changeData-'+ref).live('click', function()
	     {
	        var resu = $('#resu-'+ref).val();
	        var ssap = $('#ssap-'+ref).val();
	        var prev = $('input[name=prev_mode]:checked').val();
	        loader.fadeIn();
	        $.post(path+'poll.php', { cmd: 'changeData', u: resu, p: ssap,pr:prev,r:ref,auth: 'y'}, function(d) {
	            $('#'+ref+' #d-'+ref).fadeOut(500,function() {
	                $('#'+ref+' #d-'+ref).html(d).fadeIn(function() {
	                    loader.fadeOut();
	                });
	            })
	        });
	        return false;
	    });
	    
	    $('#design-'+ref).live('click',
	    function() {
	        $('#ds-'+ref).toggle(500);
	        $('#ds-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
	    
	    
	    $('#colorSelector-'+ref).live('click',
	    function() {
	        $(this).ColorPicker({
	            color: '#e6e6e6',
	            onShow: function(colpkr) {
	                $(colpkr).fadeIn(500);
	                return false;
	            },
	            onHide: function(colpkr) {
	                $(colpkr).fadeOut(500);
	                return false;
	            },
	            onChange: function(hsb, hex, rgb) {
	                $('#colorSelector-'+ref+' div').css('backgroundColor', '#' + hex);
	                $('#'+ref).css('backgroundColor', '#' + hex);
	            }
	        });
	    });
	    
	    
	    $('#colorSelector2-'+ref).live('click',
	    function() {
	        $(this).ColorPicker({
	            color: '#e6e6e6',
	            onShow: function(colpkr) {
	                $(colpkr).fadeIn(500);
	                return false;
	            },
	            onHide: function(colpkr) {
	                $(colpkr).fadeOut(500);
	                return false;
	            },
	            onChange: function(hsb, hex, rgb) {
	                $('#colorSelector2-'+ref+' div').css('backgroundColor', '#' + hex);
	                $('#'+ref).css('color', '#' + hex);
	            }
	        });
	    });
	    
	    
	    $('#colorSelector3-'+ref).live('click',
	    function() {
	        $(this).ColorPicker({
	            color: '#e6e6e6',
	            onShow: function(colpkr) {
	                $(colpkr).fadeIn(500);
	                return false;
	            },
	            onHide: function(colpkr) {
	                $(colpkr).fadeOut(500);
	                return false;
	            },
	            onChange: function(hsb, hex, rgb) {
	                $('#colorSelector3-'+ref+' div').css('backgroundColor', '#' + hex);
	            }
	        });
	    });
	    
	    
	    
	     $('#reset-'+ref).live('click',function() {
	        if (!confirm('You are going to style the poll with the default design,are you sure ?')) {
	            return false;
	        }
	        loader.fadeIn();
	        $.post(path+'poll.php', { cmd: 'resetStyle',r:ref,auth: 'y'}, function(d) {
	            $('#'+ref+' #d-'+ref).fadeOut(500,function() {
	                $(this).html(d).fadeIn(function() {
	                    loader.fadeOut();
	                });
	            })
	        });
	        return false;
	    });
    
	    $('#width-'+ref).live('change',function()
	     {
	     	var width = $('#width-'+ref).val();
	     	$('#'+ref).css('width',width);
	 	});
    
	    $('#saveStyle-'+ref).live('click',function()
	     {
	        var val = $('#'+ref+' input[name=buttonStyle]:checked').attr('value');
	        var bg = $('#colorSelector-'+ref+' div').attr('style');
	        var fg = $('#colorSelector2-'+ref+' div').attr('style');
	        var vg = $('#colorSelector3-'+ref+' div').attr('style');
	        var width = $('#width-'+ref).val();
	        if (val == undefined || val == '' || val == null) {
	            alert('Choose a radio button style !');
	        } else {
	            loader.fadeIn();
	            $.post(path+'poll.php', {cmd: 'changeStyle',radStyle: val,b:bg,f:fg,v:vg,w:width,r:ref,auth:'y'},
	            function(d) {
	                $('#'+ref+' #d-'+ref).fadeOut(500,function() {
	                    $(this).html(d).fadeIn(function() {
	                        loader.fadeOut();
	                    });
	                })
	            });
	        }
	        return false;
	    });
	    
	    $('#stats-'+ref).live('click',
	    function() {
	        $('#st-'+ref).toggle(500);
	        $('#st-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
    
	    $('#'+ref+' .statList').live('click',function()
	    {
	        var typo = $(this).attr('id');
	        if (typo != null && typo != undefined && typo != '') 
	        {
	            loader.fadeIn();
	            $.post(path+'poll.php', {cmd:'stats',type: typo,r:ref,auth:'y' }, function(d) 
	            {
	                $('#d-'+ref).fadeOut(500, function() 
	                {
	                    $(this).html(d).fadeIn(function() {
	                        loader.fadeOut();
	                    });
	                })
	            });
	        }
	        return false;
	    })
	    
		jQuery.download = function(url, data)
		{
			//url and data options required
			if( url && data )
			{ 
	        	loader.fadeIn();
				//data can be string of parameters or array/object
				data = typeof data == 'string' ? data : jQuery.param(data);
				//split params into form inputs
				var inputs = '';
				jQuery.each(data.split('&'), function()
				{ 
					var pair = this.split('=');
					inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
				});
				//send request
				jQuery('<form action="'+ url +'" method="post">'+inputs+'</form>')
				.appendTo('body').submit().remove();
				loader.fadeOut();
				
			};
		};

    
	    $('#csv-'+ref).live('click',
	    function() {
	        $('#dcsv-'+ref).toggle(500);
	        $('#dcsv-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
    
	    $('.csvList').live('click',function() {
	        var id = $(this).attr('id');
	        if (id != null && id != undefined && id != '')
	        {
	        	$.download('includes/export.php','t=csv&q='+id );
	        }
	        return false;
	    });
    
	    $('#xml-'+ref).live('click',
	    function() {
	        $('#dxml-'+ref).toggle(500);
	        $('#dxml-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });
	    
	        $('.xmlList').live('click',function() {
	        var id = $(this).attr('id');
	        if (id != null && id != undefined && id != '')
	        {
	        	$.download('includes/export.php','t=xml&q='+id );
	        }
	        return false;
	    });
    
	    $('#pdf-'+ref).live('click',
	    function() {
	        $('#dpdf-'+ref).toggle(500);
	        $('#dpdf-'+ref).toggleClass('open');
	        $('#'+ref+' .adBtn').hide(500);
	    });

    });

function submitForm(ref) 
{
		var loader = $('#l-'+ref);
	    var pollcontainer = $('#d-'+ref);
	    var pollForm=$('#'+ref+' .pollform');
	    var pollForm=$('#'+ref+' .pollform');
	    pollForm.live('submit',function() 
   		{
	        var selected_val = $(this).find('input[name=option]:checked').val();
	        if (selected_val != undefined)
	        {
	            loader.fadeIn();
	            $.post(path+'poll.php',{ v: $(this).serialize(),r:ref,auth: 'y'},function(d) {
	                $('#formcontainer-'+ref).fadeOut(100,function() {
	                    $(this).html(d);
	                    $(this).fadeIn(500);
	                    animateResults(ref);
	                    $('#'+ref).live('mouseout',function(){$('#thxMsg-'+ref).hide(800);});
	                    loader.fadeOut();
	                });
	            });
	        } else 
		        {
		            alert('Select an option !');
		        }
	        return false;
	    });
};

function viewResult(ref) {
		var loader =$('#l-'+ref);
	    var pollcontainer =$('#d-'+ref);
	    loader.fadeIn();
	    $.post(path+'poll.php', {result:'1',auth: 'y',r:ref},function(d) {
	        pollcontainer.fadeOut(1000,function() {
	            $(this).html(d).fadeIn();
	            animateResults(ref);
	            loader.fadeOut();
	        });
	    });
}
function vote(ref) {
	var loader =$('#l-'+ref);
    var pollcontainer =$('#d-'+ref);
    loader.fadeIn();
    $.post(path+'poll.php', {auth: 'y',r:ref},function(d) {
        pollcontainer.html(d);
        styleIt(ref);
        loader.fadeOut();
    });
}

});

function animateResults(ref) {
    $('#'+ref+' .bar').each(function() {
        var bar_width = $(this).css('width');
        $(this).css('width', '0').animate({
            width: bar_width
        },
        1000);
    });
}



function styleIt(ref) {
    replace(ref);
    $('#'+ref+' .radRep').each(function() {
        $(this).click(function() {
            $('#'+ref+' .radRep:not(this)').removeClass('checked');
            var id = $(this).attr('cId');
            var check = $('#' + id).attr('checked');
            if (!check) {
                $('#' + id).attr('checked', 'checked');
            } else {
                $('#' + id).removeAttr('checked');
            };
            $(this).toggleClass('checked');
        });
         $('#'+ref+' .pollform p label').each(function() {
            $(this).click(function() {
                var id = $(this).text();
                $(this).parent().find('.radRep').click();
            })
        })
    });
}

function replace(ref) {
    $('#'+ref+' input[name=option]').each(function() {
        $(this).css('display', 'none');
        var id = $(this).attr('id');
        $('<div cId=' + id + ' class="radRep"></div>').insertBefore(this);
    })
}

