$(document).ready(function() {
	
	$(".next_poll").live('click', nextPoll);
	$(".see_results").bind('click', seeResults);
	$("#comment_input").charCounter(120);
	
	$("#more_or_less").click(MoreOrLess);
	
	$("#form_vote").submit(function(){
    	if($("input[value!='twitter'][value!='facebook']:visible:checked").length>0){
    		return true;
    	} else {
    		$("#no_option_selected").dialog({
    			modal: true,
    			buttons: {
    				Ok: function() {
    					$(this).dialog('close');
    				}
    			}
    		});
    		return false;
    	}
    })

	if(show_results == 1){
	    seeResults();
	}else if(typeof(just_voted)!="undefined"){
	    if(just_voted == 1){
	        seeThankYou();
	    }
	}

	
	$('.gsearch').live('click',function(){
        pepepe = $(this);
        $(this).parent().append('<div class="gpanel">...loading images...</div>');
        $('.gpanel',$(this).parent()).show();
        GoogleImageField_searchImage($('input[type=text]',$(this).parent()).val());
    });

    $('#submit_poll').click(function(){

        //recolectar data
        var imgs = Array();
        $('#li_options > ul').each(
            function(indice){
                imgs[imgs.length] = [$('input[type=text]', $('#li_options > ul')).val(), $('#li_options > ul').attr('src')]
            }
        )
        //$.post()
    
    })
    
    
    $("#facebook_popup").live('click',function(e){

    	e.preventDefault();
    	
    	var link = encodeURIComponent($("#facebook_url").val());
    	
    	var title = encodeURIComponent($("#facebook_status").val());

    	    	    	
    	var popupWidth = 626;
    	
    	var popupHeight = 436;
       	
    	window.open('http://www.facebook.com/sharer.php?u='+link+'&t='+title,'sharer','width='+ popupWidth +',height='+ popupHeight +',toolbar=0,status=0,top='+(screen.height/2 - popupHeight/2)+',left='+(screen.width/2 - popupWidth/2)+'" + "');
    	
    	return false; 
    			
    })
    

    /*$('.facebook').click(function(e){
        e.preventDefault();
        loginFacebook();
    })*/


});

var pepepe = "2asd";
jQuery.fn.swap = function(b){
    b = jQuery(b)[0];
    var a = this[0];
    var t = a.parentNode.insertBefore(document.createTextNode(''), a);
    b.parentNode.insertBefore(a, b);
    t.parentNode.insertBefore(b, t);
    t.parentNode.removeChild(t);
    return this;
};

user = undefined;
user_picture = undefined;
error_message = undefined;
baseurl='';
show_results= 0;

show_loggingerror = function(){
	/*alert(error_message);*/
}

/*
selectVote	= function(id){
	$("#label_"+id).addClass("selected");
	
}
*/

more = true;
MoreOrLess = function(){
	if(more){
		$(".more").show("blind",150);
		$(this).html(text_less);
		more=false;
	} else {
		$(".more").hide("blind",150);
		$(this).html(text_more);
		more=true;
	}
	return false;
}

cleaned	= [];
FocusAndClean = function(element){
	
	if(typeof cleaned[$(element).attr("id")] == "undefined"){
		$(element).val("");
		$(element).css("color","black");
		cleaned[$(element).attr("id")]=true;
	}
}
SelectAndColor = function(element){
	$(element).select();
	$(element).css("color","black");
}
	
nextPoll = function(){
	//enviando ajax
    $.get('ajax/next_poll', {}, nextBack);
}
nextBack = function(data){
    //cambiar content
    $('.next_poll_container').html(data);
}

seeResults = function(){
    $.get(baseurl+'ajax/see_results', {'survey_id':survey_id}, seeResultsBack);
	show_results = 1;
}
seeThankYou = function(){
    $.get(baseurl+'ajax/see_thank_you', {'survey_id':survey_id}, seeResultsBack);
}
seeResultsBack = function(data){
    //cambiar content
    $('.poll_content').html(data);
}
var api = "";
loginFacebook = function(){
    FB.init(api_key, channel_path);
    FB.ensureInit(function(){
        FB.Facebook.init(api_key, channel_path);
        api = new FB.ApiClient(api_key, channel_path);
        FB.Connect.requireSession(function(a){saveFBUserData();}, true); 
    })
    return false
}

quickPoll = function(id){
	if($("#"+id).val()=='Insert title...')
	{
		$('#'+id).val('');
		return true;
	}else{
		return false;
	}	
}

quickCheck = function(id){
	if($("#"+id).val()=='Insert title...' || $("#"+id).val()=='')
	{
		alert("Please insert title");
		return false;
	}else{
		return true;
	}
}

checkVote	= function(){
	var inputs = $(":input:checked");
	if(inputs.length){
		return true;
	} else {
		alert("Please vote an option");
		return false;
	}
}

function validarEmail(valor) {
	  if (/[\w-\.]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/.test(valor)){
		  return true;
	  } else {
		  return false;
	  }
}

sendContact = function(){
	error = null;
	$("#ajax-loader").show();
		 
	if($("#name").val() == ""){
		$("#alert_contact_name").show("pulsate");
		error=true;
	}else{
		$("#alert_contact_name").hide("pulsate");
	}
	
	var mail = $("#email").val();
	
	if(validarEmail(mail)){
		$("#alert_contact_email").hide("pulsate");
	}else{
		$("#alert_contact_email").show("pulsate");
		error=true;
	}
	
	if($("#comments").val() == ""){
		$("#alert_contact_comment").show("pulsate");
		error=true;
	}else{
		$("#alert_contact_comment").hide("pulsate");
	}
	
	if(error){
		$("#ajax-loader").hide();
		return false;
	}else{
		
		var data={};
		data["name"]		= $("#name").val();
		data["email"]		= $("#email").val();
		data["comments"]	= $("#comments").val();
	
		
		$.post("http://"+location.host+"/ajax/contact",data,function(sent){
			if(sent==1){
				alert("Message sent");
				$("#ajax-loader").hide();
			}else{
				alert("Error");
				$("#ajax-loader").hide();
			}
		});
	}
}

saveQuickTitle = function(){
	var data;
	data				= {};
	data['quick_title']	= $("#title").val();
	$.post("http://"+location.host+"/ajax/record_title",data,function(sent){console.log(sent);});
}

returnQuickTitle = function(social){
	var 				data;
	data				= {};
	data['quick_title']	= $("#title").val();
	if(social=="twitter"){
		$.post("http://"+location.host+"/ajax/return_twitter_url",data,function(sent){
			location.href = sent;
		});
	} else {
		$.post("http://"+location.host+"/ajax/return_facebook_url",data,function(sent){
			location.href = sent;
		});
	}
}

save4Redirect	= function(){
	var data	= {};
	data['url']	= location.pathname;
	$.post("http://"+location.host+"/ajax/redirect_to",data);
}

var clean = true;
cleanQuickTitle = function(){
	if(clean){
		$('#title').val('');
		clean	= false;
	}
}

