var Whaddado =  Whaddado || {};
/* Whaddado Cookie js wrappers */
Whaddado.Cookie = {
    createCookie:function(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
    },
    readCookie:function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
     },
     eraseCookie : function(name) {
	this.createCookie(name,"",-1);
     }
};

Whaddado.random_length = 100000000;
Whaddado.request;
Whaddado.supports_video = function()
{
  return !!document.createElement('video').canPlayType;
}
Whaddado.notifyMessage = function(message)
{
     $("#message-text").html(message);
     $("#message-dialog").fadeIn(2000,function(){
               $(this).fadeOut(2500);
     });
}

Whaddado.delay = ( function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

Whaddado.randomNumber = function()
{
    return Math.floor(Math.random()*Whaddado.random_length);
}
Whaddado.emailValidation = function(email)
{
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(email);
}
Whaddado.init = function()
{
    $("a.btn-whaddadoit , a.whadda").live("click",Whaddado.WhaddadoIt);
    $("a.btn-followit").live("click",Whaddado.FollowIt);
    $("a.btn-unfollowit").live("click",Whaddado.UnfollowIt);
    $("a.add_friend").live("click",Whaddado.AddFriend);
    $("a.remove_friend").live("click",Whaddado.RemoveFriend);
    $("input#check_all").live("click",Whaddado.CheckAllLists)
    $("input[type=checkbox][name^='lists']").live("click",Whaddado.unCheckAll);


    // create a whaddado internally
    $(".btn-add-event").live("click",Whaddado.AddEvent);
    

    $("#input_event_keyword").live("focus",Whaddado.focusCreateEventKeyword);
   
    $("#input_event_keyword").live("keyup",Whaddado.searchForEvent);

    $("#header_what").focus(Whaddado.focusHeaderWhat);
    $("#header_where").focus(Whaddado.focusHeaderWhere);

    $("a.accept,a.deny").live("click",Whaddado.acceptDenyFriend);

    // share by email
    $(".share_email").live("click",Whaddado.shareByEmail);


    // open in a new window the external link that have rel="external"
    $("a[rel='external']").live('click', function(e) {
	window.open($(this).attr('href'));
	return false;
    });

    //sign in lightbox
   
    
    $("#whaddado-sign-in-link").live("click",Whaddado.loginWithWhaddado);
    $("#social-sign-in-link").live("click",Whaddado.loginWithSocial);

    // close hints box
    $('#closeHint').click(function(){ $('#hintbox').fadeOut('slow'); });
}
Whaddado.loginWithSocial = function(evt)
{
    $("#sign-in-box .whaddado-sign-in").slideUp("slow",function(){
        $("#sign-in-box").parent().find(".ui-dialog-buttonpane button:first").hide();
        $("#sign-in-box .social-sign-in").slideDown("slow");
    });
    return false;
}
Whaddado.loginWithWhaddado = function(evt)
{
    $("#sign-in-box .social-sign-in").slideUp("slow",function(){
        $("#sign-in-box").parent().find(".ui-dialog-buttonpane button:first").show();
        $("#sign-in-box .whaddado-sign-in").slideDown("slow");
    });
    return false;
}
Whaddado.searchForEvent = function(evt)
{
        if (  Whaddado.request != undefined)
        {
             Whaddado.request.abort();
        }
        
        Whaddado.request =  $.ajax({
            type     :  $("#form_add_event").attr("method"),
            url      :  $("#form_add_event").attr("action"),
            data     :  $("#form_add_event").serialize(),
            dataType : "json",
            success  : Whaddado.resultsSearchForEvent,
            beforeSend : Whaddado.showPreloader,
            complete   : Whaddado.hidePreloader
        });
    
    
}
Whaddado.showPreloader = function()
{

    $("#ajax_preloader").show();
}
Whaddado.hidePreloader = function()
{

    $("#ajax_preloader").hide();
}

Whaddado.resultsSearchForEvent = function(jsonResponse)
{
  
    if (jsonResponse.success == true)
    {
            if (jsonResponse.browse_event_url !='')
            {
                $("#browse_event_url").remove();
                $("#help_on_possible_new_events").after(jsonResponse.browse_event_url);
                $("#help_on_possible_new_events").hide();
                $("#help_on_added_allready").hide();
            }
            
            if ( (jsonResponse.local !='') && (jsonResponse.local != undefined) )
            {
                $("#browse_event_url").hide();
                $("#help_on_added_allready").hide();
                $("#added_allready").slideUp("slow",function()
                {
                     $("#help_on_adding").hide();
                     $("#help_on_added_allready").show();
                     
                     $(this).html(jsonResponse.local).slideDown("slow");
                     Whaddado.displayTableRows();
                });
            }
            else
            {
                $("#added_allready").slideUp("slow");
            }

            if ( (jsonResponse.google !='') && ( jsonResponse.google != undefined ) )
            {
                $("#browse_event_url").hide();
                $("#help_on_possible_new_events").hide();
                $("#possible_new_events").slideUp("slow",function()
                {
                     $("#help_on_possible_new_events").show();
                     $("#help_on_adding").hide();                    
                     $(this).html(jsonResponse.google).slideDown("slow");
                    
                });
            }
            else
            {
                 $("#possible_new_events").slideUp("slow");
            }
         
    }
}
Whaddado.displayTableRows = function()
{
    starRating.create('.rateWidget');

    $('.row:even').addClass('backrow');
	$('.hidden').hide();

	$(".reveal").each(
	function(){
			var num = $('.reveal').index(this);
			$this = $(this);
			$hidden = $('.hidden');

			$this.toggle(

					function(){                                               
						$hidden.eq(num).show();
						$(this).css('background-position', '-339px -136px');
					},

					function(){                                                
						$hidden.eq(num).hide();
						$(this).css('background-position', '-339px -118px');

					}

			)

	});
}

Whaddado.focusCreateEventKeyword= function()
{
    if ( $(this).val() ==  Whaddado.ADD_EVENT_DEFAULT_KEYWORD)
    {
        $(this).val("");
    }
}

Whaddado.acceptDenyFriend = function()
{
      var ahref = $(this);
      $.ajax({
        type :  "GET",
        url  :  $(this).attr("href"),
        dataType : "json",
        success: function(jsonResponse)
        {          
            ahref.parent().parent().fadeOut("slow",function(){
                    Whaddado.notifyMessage(jsonResponse.message);
            });
               
        }
    });
    return false;
}
Whaddado.focusHeaderWhat = function()
{
    if ( $(this).val() == 'what: gig / cafe / book' )
    {
        $(this).val("");
    }

    $(this).css("color","#8e8e8e");        
}
Whaddado.focusHeaderWhere = function()
{
    if ( $(this).val() == 'where eg: London / Paris' )
    {
        $(this).val("");
    }

    $(this).css("color","#8e8e8e");
   
}
Whaddado.AddEvent = function()
{
    $.ajax({
        type :  "GET",
        url  :  $(this).attr("href"),
        dataType : "html",
        success: function(htmlResponse)
        {
               $("body").append("<div id='add_event_container'>"+htmlResponse+"</div>");
               $("#add-event").dialog({
                            width : 700,
                            modal : true,
                            resizable:false,
                            position: 'top',
                            close:  Whaddado.cancelAddEvent,
                            buttons: {                               
                                Cancel  : Whaddado.cancelAddEvent
                            }
                        });
        }       
    });
    return false;
}

Whaddado.cancelAddEvent = function()
{
    $("#add-event").dialog("destroy");
    $("#add-event").remove();
    $("#add_event_container").empty();
}

Whaddado.CheckAllLists = function()
{
        if ($(this).attr("checked")==true)
        {
            $("input[type=checkbox][name='lists\\[\\]']").attr("checked","checked");
        }
        else
        {
            $("input[type=checkbox][name='lists\\[\\]']").attr("checked",false);
        }
}

Whaddado.unCheckAll = function()
{
    $("input#check_all").attr("checked",false);
}

Whaddado.AddFriend = function()
{
      // check to see if the user is logged in
    var link_to_add_friend = $(this).attr("href");
    $.ajax({
        type :  "GET",
        url  :  Whaddado.base_url+'action/check_if_logged_in/add_friend',
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.is_logged == true)
            {                

                $.ajax({
                    type :  'GET',
                    url  :   link_to_add_friend,
                    dataType : "json",
                    success: function(jsonResponse)
                    {
                        if (jsonResponse.success)
                        {
                            if ( (jsonResponse.friend_id != undefined) && ($("#add-friend-"+jsonResponse.friend_id).length!=0) )
                            {
                                $("#add-friend-"+jsonResponse.friend_id).hide("slow");
                            }
                            else
                            {
                                $(".add_friend").hide("slow");                              
                            }

                            Whaddado.notifyMessage(jsonResponse.message);
                        } else {
                             $(".add_friend").hide("slow");         
                            Whaddado.notifyMessage(jsonResponse.message);
                        }
                    }
                });


            return false;
        }
        else
        {
            // show the login_register window if the sign in box div is defined
            // else redirect to the login/register page
            if (  $('#sign-in-box').length != 0 )
            {
                $("#currentUrl").val(link_to_add_friend);
                $('#sign-in-box').dialog('open');
            }
            else
            {
                window.location =  Whaddado.base_url+'action/login';
            }
        }

    }
    });


        return false;
}

Whaddado.RemoveFriend = function()
{
      // check to see if the user is logged in
    var link_to_remove_friend = $(this).attr("href");
    $.ajax({
        type :  "GET",
        url  :  Whaddado.base_url+'action/check_if_logged_in/add_friend',
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.is_logged == true)
            {

                $.ajax({
                    type :  'GET',
                    url  :   link_to_remove_friend,
                    dataType : "html",
                    success: function(htmlResponse)
                    {
                                if ($("#remove_friend_container").length==0)
                                {
                                    $("body").append("<div id='remove_friend_container'></div>");
                                }

                                $("#remove_friend_container").html(htmlResponse);
                                $("#confirm_remove_friend_popup").dialog({
                                            width : 450,
                                            modal : true,
                                            resizable:false,
                                            close : Whaddado.cancelRemoveFriend,
                                            buttons: {
                                                "Remove"   : Whaddado.saveRemoveFriend,
                                                "Cancel"   : Whaddado.cancelRemoveFriend
                                            }
                                });
                    }
                });


            return false;
        }
        else
        {
            // show the login_register window if the sign in box div is defined
            // else redirect to the login/register page
            if (  $('#sign-in-box').length != 0 )
            {
                $("#currentUrl").val(link_to_remove_friend);
                $('#sign-in-box').dialog('open');
            }
            else
            {
                window.location =  Whaddado.base_url+'action/login';
            }
        }

    }
    });


        return false;
}

Whaddado.saveRemoveFriend = function()
{
      $.ajax({
        type :  $("#remove_friend_form").attr("method"),
        url  :  $("#remove_friend_form").attr("action"),
        data :  $("#remove_friend_form").serialize(),
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.success==true)
            {
                 Whaddado.cancelRemoveFriend();                 
                 $("#remove-friend-"+jsonResponse.friendId).hide("slow",function()
                 {

                       Whaddado.notifyMessage(jsonResponse.message);
                });
            }
            else
            {
                  Whaddado.cancelRemoveFriend();
                  Whaddado.notifyMessage(jsonResponse.message);
            }

           
        }
    });
    return false;
}

Whaddado.cancelRemoveFriend = function()
{
    $("#confirm_remove_friend_popup").dialog("destroy");
    $("#confirm_remove_friend_popup").remove();
    $("#remove_friend_container").empty();
}

Whaddado.FollowIt = function()
{
    // check to see if the user is logged in
    var link_to_followIt = $(this).attr("href");
    $.ajax({
        type :  "GET",
        url  :  Whaddado.base_url+'action/check_if_logged_in/followit',
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.is_logged == true)
            {
                if ($("#followit_container").length==0)
                {
                    $("body").append("<div id='followit_container'></div>");
                }

                
                $.ajax({
                    type :  'GET',
                    url  :   link_to_followIt,
                    dataType : "html",
                    success: function(htmlResponse)
                    {
                        $("#followit_container").html(htmlResponse);
                        $("#followit_popup").dialog({
                            width : 450,
                            modal : true,
                            resizable:false,
                            buttons: {
                                "Save"   : Whaddado.saveFollowIt,
                                "Cancel" : Whaddado.cancelFollowIt
                            }
                        });

                }
                });
                

            return false;
        }
        else
        {
            // show the login_register window if the sign in box div is defined
            // else redirect to the login/register page
            if (  $('#sign-in-box').length != 0 )
            {
                $("#currentUrl").val(link_to_followIt);
                $('#sign-in-box').dialog('open');
            }
            else
            {
                window.location =  Whaddado.base_url+'action/login';
            }
        }

    }
    });


return false;
}

Whaddado.UnfollowIt = function()
{
        // check to see if the user is logged in
    var link_to_unfollowIt = $(this).attr("href");
    $.ajax({
        type :  "GET",
        url  :  Whaddado.base_url+'action/check_if_logged_in/followit',
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.is_logged == true)
            {
                if ($("#unfollowit_container").length==0)
                {
                    $("body").append("<div id='unfollowit_container'></div>");
                }


                $.ajax({
                    type :  'GET',
                    url  :   link_to_unfollowIt,
                    dataType : "html",
                    success: function(htmlResponse)
                    {
                        $("#unfollowit_container").html(htmlResponse);
                        $("#unfollowit_popup").dialog({
                            width : 450,
                            modal : true,
                            resizable:false,
                            buttons: {
                                "Ok"     : Whaddado.saveUnfollowIt,
                                "Cancel" : Whaddado.cancelUnfollowIt
                            }
                        });

                }
                });


            return false;
        }
        else
        {
            // show the login_register window if the sign in box div is defined
            // else redirect to the login/register page
            if (  $('#sign-in-box').length != 0 )
            {
                $("#currentUrl").val(link_to_unfollowIt);
                $('#sign-in-box').dialog('open');
            }
            else
            {
                window.location =  Whaddado.base_url+'action/login';
            }
        }

    }
    });
    return false;
}
Whaddado.saveUnfollowIt = function()
{
      $.ajax({
        type :  $("#remove_unfollow_user").attr("method"),
        url  :  $("#remove_unfollow_user").attr("action"),
        data :  $("#remove_unfollow_user").serialize(),
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.success==true)
            {
                 $("#unfollowit-"+jsonResponse.userId).hide("slow",function()
                 {
                       Whaddado.notifyMessage(jsonResponse.message);
                });
            }
            Whaddado.cancelUnfollowIt();
        }
    });
    return false;
}
Whaddado.cancelUnfollowIt = function()
{
    $("#unfollowit_popup").dialog("destroy");
    $("#unfollowit_popup").remove();
    $("#unfollowit_container").empty();
}

Whaddado.WhaddadoIt = function()
{
    // check to see if the user is logged in
    var link_to_whaddadoIt = $(this).attr("href");
    $.ajax({
        type :  "GET",
        url  :  Whaddado.base_url+'action/check_if_logged_in/whaddadoit',
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.is_logged == true)
            {
                 Whaddado.Event.showListInterestsPopup();
                 return false;
            }
        else
        {
            // show the login_register window if the sign in box div is defined
            // else redirect to the login/register page
            if (  $('#sign-in-box').length != 0 )
            {
                $("#currentUrl").val(link_to_whaddadoIt);
                $('#sign-in-box').dialog('open');
            }
            else
            {
                window.location =  Whaddado.base_url+'action/login';
            }
        }

    }
    });
    

return false;
}

Whaddado.cancelFollowIt = function()
{
    $("#followit_popup").dialog("destroy");
    $("#followit_popup").remove();
    $("#followit_container").empty();
}

Whaddado.cancelWhaddadoIt = function()
{
    $("#whaddadoit_popup").dialog("destroy");
    $("#whaddadoit_popup").remove();
    $("#whaddadoit_container").empty();
}


Whaddado.saveFollowIt = function()
{
    $.ajax({
        type :  $("#followit_form").attr("method"),
        url  :  $("#followit_form").attr("action"),
        data :  $("#followit_form").serialize(),
        dataType : "json",
        success: function(jsonResponse)
        {
            if (jsonResponse.success==true)
            {
                 $("#followit-"+jsonResponse.userId).hide("slow",function()
                 {
                       Whaddado.notifyMessage(jsonResponse.message);
                 });

                 if ($("#followit2-"+jsonResponse.userId).length > 0) {
                     $("#followit2-"+jsonResponse.userId).hide("slow",function()
                     {
                           Whaddado.notifyMessage(jsonResponse.message);
                     });
                 }
            }
            Whaddado.cancelFollowIt();
        }
    });
    return false;
}

Whaddado.saveWhaddadoIt = function()
{  

    $.ajax({
        type :  $("#whaddadoit_form").attr("method"),
        url  :  $("#whaddadoit_form").attr("action"),
        data :  $("#whaddadoit_form").serialize(),
        dataType : "json",
        success: function(jsonResponse)
        {        
            if ( $(".num").length != 0 )
            {
                var nr = parseInt($(".num").html())+1;
                $(".num").html(nr);
                
                $("#whaddado-it-"+jsonResponse.eventId).slideUp("slow",function(){
                    $(this).after('<span class="whadda">Added</span>').remove();
                });

            }
            else
            {
                $("#whaddado-it-"+jsonResponse.eventId).hide("slow");
            }

            Whaddado.notifyMessage(jsonResponse.message);
            Whaddado.cancelWhaddadoIt();
        }
    });
    return false;
}

Whaddado.shareByEmail = function()
{
     if ($("#share_email_container").length==0)
     {
         $("body").append("<div id='share_email_container'></div>");
     }

     $.ajax({
             type :  'GET',
             url  :   $(this).attr("href"),
             dataType : "html",
             success: function(htmlResponse)
             {
                        $("#share_email_container").html(htmlResponse);
                        $("#share_email_popup").dialog({
                            width : 600,
                            modal : true,
                            resizable:false,
                            buttons: {
                                "Send"   : Whaddado.sendShareEmail,
                                "Cancel" : Whaddado.cancelShareEmail
                            }
                        });

            }
       });
                
    return false;
}
Whaddado.sendShareEmail = function()
{
    // check to see if the user is logged in or not
    var form_valid =  true;
    var error_message = '';
    $("#share_email_form_error").html('').hide();
    
    if ( $("#pram_name").length > 0 )
    {
        if (jQuery.trim($("#pram_name").val())=='')
        {
            form_valid =  false;
            error_message += 'Please enter your  name <br/>' ;
        }
    }
    
    if ( $("#pram_email").length > 0 )
    {
        if (!Whaddado.emailValidation($("#pram_email").val()))
        {
            form_valid =  false;
            error_message += 'Please enter your valid email <br/>';
        }
    }


    if (jQuery.trim($("#pram_friendsname").val())=='')
    {
            form_valid =  false;
            error_message += 'Please enter your friend name <br/>' ;
    }

    if (!Whaddado.emailValidation($("#pram_friendsemail").val()))
    {
            form_valid =  false;
            error_message += 'Please enter a valid email for your friend <br/>';
    }

    if (form_valid == true)
    {
        $.ajax({
            type :  $("#share_email_form").attr("method"),
            url  :  $("#share_email_form").attr("action"),
            data :  $("#share_email_form").serialize(),
            dataType : "json",
            success: function(jsonResponse)
            {
                if (jsonResponse.success == true)
                {
                    Whaddado.cancelShareEmail();
                    Whaddado.notifyMessage(jsonResponse.message);
                }
                else
                {
                    $("#share_email_form_error").html(jsonResponse.message).show("slow");
                }

            }
        });
    }
    else
    {
        $("#share_email_form_error").html(error_message).show("slow");
    }
    return false;
}

Whaddado.cancelShareEmail = function()
{
    $("#share_email_popup").dialog("destroy");
    $("#share_email_popup").remove();
    $("#share_email_container").empty();
}

$(document).ready(Whaddado.init);
